Monday, March 31, 2008

var Variable

"var" is used to implicitly type a new variable. (Implicit simply means 'not directly stated'.)
Example:
var x = "Mark"; // Implicitly declared. 
string x = "Mark"; // Explicitly declared.
You will most likely never see the example above. So why do we need this?

C# 3.0 now is able to create and type classes on the fly. These new classes and properties of the class are instantiated and populated and assigned to a var variable.

Example:
var person = new { FirstName = "Mark", LastName = "Moeykens" }; 
string name = person.FirstName;
Here a new class is instantiated and assigned to the "person" variable. In this case it is impossible to explicitly state the type of the "person" variable.

Note: var variables cannot be public.

More Info: MSDN: var (C# Reference) Blog Post: Class and Collection Initializers

Sunday, March 30, 2008

Auto-Implemented Properties

You do not have to declare private variables to store values of your class properties.
Before:
public class Person 
{
     private string name;
     public string Name
     {
         get { return name; }
         set { name = value; }
     } 
}
After:
public class Person 
{
     public string Name { get; set; } 
}
More Info: MSND: Auto-Implemented Properties

Saturday, March 29, 2008

Ternary Operator ( ? : )

The Ternary Operator is another form of an if statement. (Ternary means "consisting of 3 things".)
The format is: condition ? true part : false part

For example, this:
string name = paramName != null ? paramName : "No name provided"; 
Is basically the same as this:
string name; 
if (paramName != null) 
{
     name = paramName; 
} 
else 
{
     name = "No name provided"; 
}
More info: MSDN: Ternary Operator

Friday, March 28, 2008

Coalesce Operator (??)

Coalesce means to merge or unite things. When you put this operator between two variables, it will return the first one that is not null.

Example:
string name = firstName ?? lastName ?? middleName ?? string.Empty;
This if statement does the same thing:
string name = string.Empty; 
if (firstName != null)
      name = firstName; 
elseif (lastName != null)
     name = lastName; 
elseif (middleName!= null)
     name = middleName;
More Info: MSDN: ?? Operator
Thanks goes to my friend, Rich, for this info.