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());
}
}