Regex.Replace(StringName.Trim(), @",", @" and ", RegexOptions.IgnoreCase);
Showing posts with label Asp.Net C#. Show all posts
Showing posts with label Asp.Net C#. Show all posts
Tuesday, 27 March 2018
Sunday, 11 February 2018
Difference between == and .Equals method in c#
For Value Type:
== and .Equals() method usually compare two objects by value.
For Example:
int x = 20;
int y = 20;
Console.WriteLine( x == y);
Console.WriteLine(x.Equals(y));
Output:
True
True
For Reference Type:
== performs an identity comparison,
i.e. it will only return true
if both references point to the same object.
While Equals() method is expected to
perform a value comparison, i.e. it will
return true if the references point
to objects that are equivalent.
For Example:
StringBuilder s1 = new StringBuilder(“Yes”);
StringBuilder s2 = new StringBuilder(“Yes”);
Console.WriteLine(s1 == s2);
Console.WriteLine(s1.Equals(s2));
Output:
False
True
In above example, s1 and s2 are different objects hence “==” returns
false, but they are equivalent hence “Equals()”
method returns true. Remember there is an exception of this rule,
i.e. when you use “==” operator with string class it
compares value rather than identity.
When to use “==” operator and when to use “.Equals()” method?
For value comparison, with Value Type use “==” operator
and use “Equals()” method while performing value comparison
with Reference Type.
== and .Equals() method usually compare two objects by value.
For Example:
int x = 20;
int y = 20;
Console.WriteLine( x == y);
Console.WriteLine(x.Equals(y));
Output:
True
True
For Reference Type:
== performs an identity comparison,
i.e. it will only return true
if both references point to the same object.
While Equals() method is expected to
perform a value comparison, i.e. it will
return true if the references point
to objects that are equivalent.
For Example:
StringBuilder s1 = new StringBuilder(“Yes”);
StringBuilder s2 = new StringBuilder(“Yes”);
Console.WriteLine(s1 == s2);
Console.WriteLine(s1.Equals(s2));
Output:
False
True
In above example, s1 and s2 are different objects hence “==” returns
false, but they are equivalent hence “Equals()”
method returns true. Remember there is an exception of this rule,
i.e. when you use “==” operator with string class it
compares value rather than identity.
When to use “==” operator and when to use “.Equals()” method?
For value comparison, with Value Type use “==” operator
and use “Equals()” method while performing value comparison
with Reference Type.
Return Multiple values from a function in C#
In C#, There are 4 ways to return multiple values from a C# function.
- Using KeyValue pair
- Using ref/out parameters
- Using Struct or Class
- Using Tuple
1. Using KeyValue pair:
class Program
{
static void Main(string[] args)
{
int int1 = 15;
int int2 = 25;
var result = Add_Multiply(int1, int2);
Console.WriteLine(result.Key);
Console.WriteLine(result.Value);
}
private static KeyValuePair<int, int> Add_Multiply(int int1, int int2)
{
var KeyValuePair = new KeyValuePair<int, int>(int1 + int2, int1 * int2);
return KeyValuePair;
}
}
Output:
40
375
375
2.a. Using Ref Parameter:
class Program
{
static void Main(string[] args)
{
int int1 = 15;
int int2 = 25;
int add = 0;
int multiply = 0;
Add_Multiply(int1, int2, ref add, ref multiply);
Console.WriteLine(add);
Console.WriteLine(multiply);
}
private static void Add_Multiply(int int1, int int2, ref int add, ref int multiply)
{
add = int1 + int2;
multiply = int1 * int2;
}
}
40
375
375
2.b. Using Out Parameter:
class Program
{
static void Main(string[] args)
{
int int1 = 15;
int int2 = 25;
int add = 0;
int multiply = 0;
Add_Multiply(int1, int2, out add, out multiply);
Console.WriteLine(add);
Console.WriteLine(multiply);
}
private static void Add_Multiply(int int1, int int2, out int add, out int multiply)
{
add = int1 + int2;
multiply = int1 * int2;
}
}
Output:
40
375
375
3.a. Using Struct:
class Program
{
struct Result
{
public int add;
public int multiply;
}
static void Main(string[] args)
{
int int1 = 53;
int int2 = 17;
var result = Add_Multiply(int1, int2);
Console.WriteLine(result.add);
Console.WriteLine(result.multiply);
}
private static Result Add_Multiply(int int1, int int2)
{
var result = new Result
{
add = int1 + int2,
multiply = int1 * int2
};
return result;
}
}
Output:
70
901
901
3.b. Using Class:
struct Result
{
public int add;
public int multiply;
}
static void Main(string[] args)
{
int int1 = 13;
int int2 = 27;
var result = Add_Multiply(int1, int2);
Console.WriteLine(result.add);
Console.WriteLine(result.multiply);
}
private static Result Add_Multiply(int int1, int int2)
{
var result = new Result
{
add = int1 + int2,
multiply = int1 * int2
};
return result;
}
}
Output:
40
351
351
4. Using Tuple:
class Program
{
static void Main(string[] args)
{
int int1 = 25;
int int2 = 28;
var result = Add_Multiply(int1, int2);
Console.WriteLine(result.Item1);
Console.WriteLine(result.Item2);
}
private static Tuple<int, int> Add_Multiply(int int1, int int2)
{
var tuple = new Tuple<int, int>(int1 + int2, int1 * int2);
return tuple;
}
}
Remove Duplicate characters from String in C#
class Program
{
static void Main()
{
string value1 = RemoveDuplicateChars("Csharpstar");
string value2 = RemoveDuplicateChars("Google");
string value3 = RemoveDuplicateChars("Yahoo");
string value4 = RemoveDuplicateChars("CNN");
string value5 = RemoveDuplicateChars("Line1\nLine2\nLine3");
Console.WriteLine(value1);
Console.WriteLine(value2);
Console.WriteLine(value3);
Console.WriteLine(value4);
Console.WriteLine(value5);
}
static string RemoveDuplicateChars(string key)
{
// --- Removes duplicate chars using string concats. ---
// Store encountered letters in this string.
string table = "";
// Store the result in this string.
string result = "";
// Loop over each character.
foreach (char value in key)
{
// See if character is in the table.
if (table.IndexOf(value) == -1)
{
// Append to the table and the result.
table += value;
result += value;
}
}
return result;
}
}
Input: Google
Output: Gogle
Output: Gogle
Saturday, 16 December 2017
Asp .Net Page Life Cycle
ASP.NET Page Life Cycle Events
When a page request is sent to the Web server, the page is run through a series of events during its creation and disposal.
In this article, I will discuss in detail the ASP.NET page life cycle Events
(1) PreInit
The entry point of the page life cycle is the pre-initialization phase called “PreInit”. This is the only event where programmatic access to master pages and themes is allowed. You can dynamically set the values of master pages and themes in this event. You can also dynamically create controls in this event.
EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_PreInit(object sender, EventArgs e)
{
// Use this event for the following:
// Check the IsPostBack property to determine whether this is the first time the page is being processed.
// Create or re-create dynamic controls.
// Set a master page dynamically.
// Set the Theme property dynamically.
}
(2)Init
This event fires after each control has been initialized, each control’s UniqueID is set and any skin settings have been applied. You can use this event to change initialization values for controls. The “Init” event is fired first for the most bottom control in the hierarchy, and then fired up the hierarchy until it is fired for the page itself.
EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page
protected void Page_Init(object sender, EventArgs e)
{
// Raised after all controls have been initialized and any skin settings have been applied.
// Use this event to read or initialize control properties.
// Use this event to read or initialize control properties.
}
(3)InitComplete
Raised once all initializations of the page and its controls have been completed. Till now the viewstate values are not yet loaded, hence you can use this event to make changes to view state that you want to make sure are persisted after the next postback
EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page
protected void Page_InitComplete(object sender, EventArgs e)
{
// Raised by the Page object. Use this event for processing tasks that require all initialization be complete.
}
(4)PreLoad
Raised after the page loads view state for itself and all controls, and after it processes postback data that is included with the Request instance
Loads ViewState : ViewState data are loaded to controls
Note : The page viewstate is managed by ASP.NET and is used to persist information over a page roundtrip to the server. Viewstate information is saved as a string of name/value pairs and contains information such as control text or value. The viewstate is held in the value property of a hidden <input> control that is passed from page request to page request.
Loads Postback data : postback data are now handed to the page controls
Note : During this phase of the page creation, form data that was posted to the server (termed postback data in ASP.NET) is processed against each control that requires it. Hence, the page fires the LoadPostData event and parses through the page to find each control and updates the control state with the correct postback data. ASP.NET updates the correct control by matching the control’s unique ID with the name/value pair in the NameValueCollection. This is one reason that ASP.NET requires unique IDs for each control on any given page.
Loads ViewState : ViewState data are loaded to controls
Note : The page viewstate is managed by ASP.NET and is used to persist information over a page roundtrip to the server. Viewstate information is saved as a string of name/value pairs and contains information such as control text or value. The viewstate is held in the value property of a hidden <input> control that is passed from page request to page request.
Loads Postback data : postback data are now handed to the page controls
Note : During this phase of the page creation, form data that was posted to the server (termed postback data in ASP.NET) is processed against each control that requires it. Hence, the page fires the LoadPostData event and parses through the page to find each control and updates the control state with the correct postback data. ASP.NET updates the correct control by matching the control’s unique ID with the name/value pair in the NameValueCollection. This is one reason that ASP.NET requires unique IDs for each control on any given page.
EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page
protected override void OnPreLoad(EventArgs e)
{
// Use this event if you need to perform processing on your page or control before the Load event.
// Before the Page instance raises this event, it loads view state for itself and all controls, and
// then processes any postback data included with the Request instance.
// then processes any postback data included with the Request instance.
}
(5)Load
The important thing to note about this event is the fact that by now, the page has been restored to its previous state in case of postbacks. Code inside the page load event typically checks for PostBack and then sets control properties appropriately. This method is typically used for most code, since this is the first place in the page lifecycle that all values are restored. Most code checks the value of IsPostBack to avoid unnecessarily resetting state. You may also wish to call Validate and check the value of IsValid in this method. You can also create dynamic controls in this method.
EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page
protected void Page_Load(object sender, EventArgs e)
{
// The Page calls the OnLoad event method on the Page, then recursively does the same for each child
// control, which does the same for each of its child controls until the page and all controls are loaded.
// control, which does the same for each of its child controls until the page and all controls are loaded.
// Use the OnLoad event method to set properties in controls and establish database connections.
}
(6)Control (PostBack) event(s)
ASP.NET now calls any events on the page or its controls that caused the PostBack to occur. This might be a button’s click event or a dropdown’s selectedindexchange event, for example.
These are the events, the code for which is written in your code-behind class(.cs file).
EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page
protected void Button1_Click(object sender, EventArgs e)
{
// This is just an example of control event.. Here it is button click event that caused the postback
}
(7)LoadComplete
This event signals the end of Load.
EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page
protected void Page_LoadComplete(object sender, EventArgs e)
{
// Use this event for tasks that require that all other controls on the page be loaded.
}
(8)PreRender
Allows final changes to the page or its control. This event takes place after all regular PostBack events have taken place. This event takes place before saving ViewState, so any changes made here are saved.
For example : After this event, you cannot change any property of a button or change any viewstate value. Because, after this event, SaveStateComplete and Render events are called.
EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page
protected override void OnPreRender(EventArgs e)
{
// Each data bound control whose DataSourceID property is set calls its DataBind method.
// The PreRender event occurs for each control on the page. Use the event to make final
// changes to the contents of the page or its controls.
// changes to the contents of the page or its controls.
}
(9)SaveStateComplete
Prior to this event the view state for the page and its controls is set. Any changes to the page’s controls at this point or beyond are ignored.
EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page
protected override void OnSaveStateComplete(EventArgs e)
{
// Before this event occurs, ViewState has been saved for the page and for all controls.
// Any changes to the page or controls at this point will be ignored.
// Any changes to the page or controls at this point will be ignored.
// Use this event perform tasks that require view state to be saved, but that do not make any changes to controls.
}
(10)Render
This is a method of the page object and its controls (and not an event). At this point, ASP.NET calls this method on each of the page’s controls to get its output. The Render method generates the client-side HTML, Dynamic Hypertext Markup Language (DHTML), and script that are necessary to properly display a control at the browser.
Note: Right click on the web page displayed at client’s browser and view the Page’s Source. You will not find any aspx server control in the code. Because all aspx controls are converted to their respective HTML representation. Browser is capable of displaying HTML and client side scripts.
EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page
// Render stage goes here. This is not an event
(11)UnLoad
This event is used for cleanup code. After the page’s HTML is rendered, the objects are disposed of. During this event, you should destroy any objects or references you have created in building the page. At this point, all processing has occurred and it is safe to dispose of any remaining objects, including the Page object.
Cleanup can be performed on-
(a)Instances of classes i.e. objects
(b)Closing opened files
(c)Closing database connections.
EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page
protected void Page_UnLoad(object sender, EventArgs e)
{
// This event occurs for each control and then for the page. In controls, use this event to do final cleanup
// for specific controls, such as closing control-specific database connections.
// for specific controls, such as closing control-specific database connections.
// During the unload stage, the page and its controls have been rendered, so you cannot make further
// changes to the response stream.
// changes to the response stream.
//If you attempt to call a method such as the Response.Write method, the page will throw an exception.
}
}
C# Version History
C# feature & Update version by version
C# List features
C# 1.0
Microsoft released the first version of C# with Visual Studio 2002. Use of Managed Code was introduced with this version. C# 1.0 was the first language that developer adopted to build .NET applications.
C# 2.0
Microsoft released the second version of C# language with Visual Studio 2005. C# 2.0 has introduced few new features in this edition which helped the developers to code their applications in more generic way. Here are the new features that were introduced with C# 2.0:
- Generics
- Anonymous Methods
- Nullable Type
- Partial Class
- Covariance and Contravariance
C# 3.0
Visual Studio 2008 came with C# version 3.0 and it has a bunch of new features. It was the life-changing the language for Microsoft platform developers to build their applications. Till now, many developers are still using this version to build their apps. The new features that came with C# 3.0 were:
- Lambda Expression
- Extension Methods
- Expression Trees
- Anonymous Types
- LINQ
- Implicit Type (var)
C# 4.0
Though C# 4.0 was released with Visual Studio 2010 with .NET Framework 4, very few developers use its new features till date. Here is a list of new features of C# that came with this version:
- Late Binding
- Named Arguments
- Optional Parameters
- More COM Support
C# 5.0
Visual Studio 2012 came up with C# 5.0 and it was made available to the audience in the year 2012. In C# version 5.0, there are two key features:
- Async Programming
- Caller Information
C# 6.0
The C# 6.0 release contained many features that improve productivity for developers. Some of the features in this release were:
- Read-only Auto-properties
- String Interpolation
- await in catch and finally blocks
- index initializers
- Null- conditional operators
C# 7.0
C# 7.0 is the current version (at the time of writing this article) which adds a number of new features to the C# language:
- Pattern Matching
- out variables
- throw Expressions
- Tuples
- ref locals & returns and few more…
C# 7.1
C# 7.1 is the new version (at the time of updating this article) which again adds a couple of new features to the C# language:
- Asynchronous Main – Main could be void or int and contain arguments as a string array.
- Default Literal – Visual Basic and C# have similar features, but there are certain differences in the languages, i.e. C# has null, while VB.NET has Nothing.
That’s all as per this post is concerned. We will update this list as soon as new version is out in the market.
C# version history in tabular format for quick view:
| Version | Date | .NET Framework | Visual Studio |
|---|---|---|---|
| C# 1.0 | Jan-02 | .NET Framework 1.0 | Visual Studio .NET 2002 |
| C# 1.1/1.2 | Apr-03 | .NET Framework 1.1 | Visual Studio .NET 2003 |
| C# 2.0 | Nov-05 | .NET Framework 2.0 | Visual Studio .NET 2005 |
| C# 3.0 | Nov-07 | .NET Framework 2.0 (Except LINQ),.NET Framework 3.0 (Except LINQ),
.NET Framework 3.5
| Visual Studio .NET 2008,Visual Studio .NET 2010 |
| C# 4.0 | Apr-10 | .NET Framework 4.0 | Visual Studio .NET 2010 |
| C# 5.0 | Aug-12 | .NET Framework 4.5 | Visual Studio .NET 2012/2013 |
| C# 6.0 | Jul-15 | .NET Framework 4.6 | Visual Studio .NET 2015 |
| C# 7.0 | Mar-17 | .NET Framework 4.6.2 | Visual Studio .NET 2017 |
Subscribe to:
Posts (Atom)
React Hooks - custom Hook
v CustomHook Ø React allows us to create our own hook which is known as custom hook. Example – 1 localStorage Demo Step-1 Create ...
-
Garbage collection is a low-priority process that serves as an automatic memory manager which manages the allocation and release of memory...
-
private static Regex _compiledUnicodeRegex = new Regex(@"[^\u0000-\u007F]", RegexOptions.Compiled); public static Strin...
-
SELECT name , email , COUNT (*) FROM users GROUP BY name , email HAVING COUNT (*) > 1