Wednesday, May 20, 2009

Match two strings

Many people don't realize that they can compare strings using: OrdinalIgnoreCase instead of having to do someString.ToUpper().
This removes the additional string allocation overhead.
if( myString.ToUpper() == theirString.ToUpper() )
{ ... }
becomes
if( myString.Equals( theirString, StringComparison.OrdinalIgnoreCase )
{ ... }

Or you can use:
"string".equals("String", StringComparison.InvariantCultureIgnoreCase);

anonymous types can infer property names from the variable name

string hello = "world"; 
var o = new { hello };
Console.WriteLine(o.hello);

Trick : Environment.FailFast()

If you want to exit your program without calling any finally blocks or finalizers use :
Environment.FailFast()

Tuesday, May 19, 2009

New Trick : ?? operator (Null - coalescing operator)

C# 2.0 has a nice ?? operator that works as a shortcut for:

string value1 = null;string value2 = "Test1";string result = value1 != null ? value1 : value2;
which causes result containing Test1 or the second value.

In C# you can shortcut this special null comparison case with the new ??:
string result = value1 ?? value2;

This operator is called the null-coalescing operator.

you can chain these operators together so you can do a whole bunch of null comparisons in a single stroke.
For example, We frequently look for a few different querystring variables in a page:

///// Generally programmers do like this
if (Request.QueryString["RP"] != null)
{
qrystring = Request.QueryString["RP"].ToString();
}
else
{
qrystring = "I am blank";
}

//The above If-Else version can be written in one line :
qrystring = Request.QueryString["RP"] ?? "I m blank";

//Another version with Multiple quertystrings which removes the usage of Multilple Nested Ifs:
string partner = Request.QueryString["GoogleId"] ??
Request.QueryString["PartnerId"] ??
Request.QueryString["UserKey"] ??
string.Empty;

which still yields a valid result for the first non-null querystring or if nothing is found returning "".

The ?? operator defines the default value to be returned when a nullable type is assigned to a non-nullable type. If you try to assign a nullable value type to a non-nullable value type without using the ?? operator, you will generate a compile-time error. If you use a cast, and the nullable value type is currently undefined, an InvalidOperationException exception will be thrown.

A good trick using the null coalesce operator (??) is to automagically instantiate collections.
private IList _foo;
public IList ListOfFoo
{
get
{
return _foo ?? (_foo = new List());
}
}

Monday, March 16, 2009

Generic Method for Parsing a value into an Enum.

public static T ParseEnum(string value) 
 { 
    return (T)Enum.Parse(typeof(T), value); 
 } 

 usage: MyStatusEnum status = ParseEnum(reader["Status"].ToString());

Thursday, October 30, 2008

Difference between two Dates in C#.NET ?

To find the difference between two dates is very simple in VB — By using DateDiff method. But in C#, there is no direct method to do so. but there is a way to achive this. For this we need to understand TimeSpan Class.

The following code snippet will show you how to find the difference.

DateTime startTime = DateTime.Now;
DateTime endTime = DateTime.Now.AddSeconds( 75 );
TimeSpan span = endTime.Subtract ( startTime );
Console.WriteLine( “Time Difference (seconds): ” + span.Seconds );
Console.WriteLine( “Time Difference (minutes): ” + span.Minutes );
Console.WriteLine( “Time Difference (hours): ” + span.Hours );
Console.WriteLine( “Time Difference (days): ” + span.Days );

By concatenating all this you will get the difference between two dates. You can also use span.Duration().
There are certain limitations to. The TimeSpan is capable of returning difference interms of Days, Hours, mins and seconds only. It is not having a property to show difference interms of Months and years.