Wednesday, April 30, 2008

LINQ to XML - Namespaces

Adding on to yesterday's post, you might come across xml that has a namespace defined. You'll have to handle this with the XNamespace object.
XML with namespace:
<?xml version="1.0" standalone="yes"?>
<MyDataSet xmlns="http://tempuri.org/MyDataSet.xsd">
  <Person>
    <PersonId>1</PersonId>
    <PersonName>Mark</PersonName>
  </Person>
  <Person>
    <PersonId>2</PersonId>
    <PersonName>Matt</PersonName>
  </Person>
</MyDataSet>
Querying the XML:
XDocument ds = XDocument.Load(Resources.SimpleXmlFileWithNamespacePath);
XNamespace ns = "http://tempuri.org/MyDataSet.xsd";
XName xNamePerson = ns + "Person";
XName xNamePersonName = ns + "PersonName";

var personNames = from person in ds.Descendants(xNamePerson)
              select new
              {
                  PersonName = person.Element(xNamePersonName).Value
              };
The XName class provides a way to combine a namespace and an element name.

More Info: MSDN: XNamespace Class
MSDN: XName Class

Tuesday, April 29, 2008

LINQ to XML

There's a lot you can do with LINQ to XML. It will be your alternative to selecting xml nodes using XPath queries. I'm going to show you just a little bit at a time.

Say you wanted to get all PersonName values from this xml:
<Persons>
  <Person>
    <PersonId>1</PersonId>
    <PersonName>Mark</PersonName>
  </Person>
  <Person>
    <PersonId>2</PersonId>
    <PersonName>Matt</PersonName>
  </Person>
</Persons>
You can simply write your LINQ like this:
XDocument ds = XDocument.Load("PersonsFile.xml");

var persons = from eachPerson in ds.Descendants("Person") 
select new 
{
    PersonName = eachPerson.Element("PersonName").Value
};
This is two lines of code. Notice the semicolon at the very end.

XDocument is like your new XmlDocument class. It loads an xml file.
LINQ is then used to find all elements (descendants) that are named "Person".

So what the heck is happening with that select new? Remember the post on anonymous types? That's what this LINQ to XML is creating; a collection of anonymous types (classes). The breakdown of what this LINQ statement is saying:
1. Give me a collection of elements that match "Person" which you can reference from the eachPerson variable.
2. Create an anonymous class and add a property called "PersonName".
3. "PersonName" is assigned a value from the eachPerson match.
4. Now add that new anonymous class to the var collection called "persons".

The result is a collection of typed objects that you can iterate through later on:
List<string> array = new List<string>();
foreach (var person in persons)
{
    array.Add(person.PersonName);
}

This is a whole different shift in thinking. To get used to it I suggest you write some code and create a bunch of anonymous classes until you are comfortable with that concept. Create anonymous classes, add properties. Access and use those properties and so on. Once you feel good and comfortable with that you can move on to learning more about LINQ.
More Info: MSDN:

Friday, April 25, 2008

XmlWriter

To create this in code:
<?xml version="1.0" encoding="utf-16"?><Person><FirstName>Mark</FirstName><LastName>Moeykens</LastName></Person>
You can code it this way:
StringBuilder sb = new StringBuilder();
using(XmlWriter writer = XmlTextWriter.Create(sb))
{
    writer.WriteStartElement("Person");
    writer.WriteElementString("FirstName", "Mark");
    writer.WriteElementString("LastName", "Moeykens");
    writer.WriteEndDocument();
}
Console.Write(sb.ToString());
The
<?xml version="1.0" encoding="utf-16"?>
bugs me though. I never seem to have a use for it in my code so let's get rid of it.

To do that, we have to introduce some settings for our writer using the XmlWriterSettings class then pass it into the XmlTextWriter.Create method.
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;

StringBuilder sb = new StringBuilder();
using(XmlWriter writer = XmlTextWriter.Create(sb, settings))
{
    writer.WriteStartElement("Person");
    writer.WriteElementString("FirstName", "Mark");
    writer.WriteElementString("LastName", "Moeykens");
    writer.WriteEndDocument();
}
Console.Write(sb.ToString());
Output:
<Person><FirstName>Mark</FirstName><LastName>Moeykens</LastName></Person>
That's better. Now let's add another setting to get the elements on their own line and indented:
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
settings.Indent = true;

StringBuilder sb = new StringBuilder();
using(XmlWriter writer = XmlTextWriter.Create(sb, settings))
{
    writer.WriteStartElement("Person");
    writer.WriteElementString("FirstName", "Mark");
    writer.WriteElementString("LastName", "Moeykens");
    writer.WriteEndDocument();
}
Console.Write(sb.ToString());
Output:
<Person>
  <FirstName>Mark</FirstName>
  <LastName>Moeykens</LastName>
</Person>
There we go, this looks much better!

More Info: MSDN: Creating XML Writers

Thursday, April 24, 2008

Predicate Delegate

To pose a problem, let's create a strongly typed list of the Person class:
public class Person
{
    public string FirstName { get; set; }
}

// ...

List<Person> people = new List<Person>
              {
                  new Person("Mark"),
                  new Person("Rod"),
                  new Person("Matt"),
                  new Person("Rich"),
                  new Person("Jake")
              };
I used a collection initializer to populate a new typed generic List.

Ok, so how would you do a search in that collection and return the Person class that represents "Rod"? Luckily this generic list class has 5 different Find type methods (9 if you count the overloads).

Take a look at them though. They take a "Predicate". What the heck is this "Predicate"?

The word "predicate" is a term used in the subject of Logic that basically means
"to say something is true or false"
.

A predicate in .NET is a delegate that represents a method you write to check if a condition is true or false. So your predicate method will take in one parameter, evaluate it, and then return a true or false. Let's see what this might look like:
// Your predicate function.
private bool FindRod(Person person)
{
    if (person.FirstName == "Rod")
        return true;
    return false;
}

// ...

Person foundPerson = people.Find(FindRod);
Now when you call the Find method, just pass in the name of your predicate method. The Find method will loop through all the items in the collection and run your predicate method until a true is returned.

Now that you have the basics down, I think you can take a look at the other Find methods and be able to tell what they do.

More Info: MSDN: Predicate(T) Generic Delegate

Wednesday, April 23, 2008

Delegates

The word "delegate" means "to represent another". A delegate in .NET is just another type, like class or string is a type. A delegate "represents another" method. I'll give examples of using a delegate next to a class so you can see some similarities in how they are used.

Declaring
// 1. Declare it.
public delegate int PerformCalculation(int x, int y);
public class Person
{
    public string GetName()
    {
        return "Mark";
    }
}
So it is like declaring any other type except instead of a variable name, you will be using a method signature. The method name (PerformCalculation) is how you reference the delegate.
You declare the variable "PerformCalculation" as the type "delegate". Think of it as defining a method signature (just like you would in an interface) and then putting the word "delegate" in front of it.

Assigning a Value
public void CreateAndUse()
{
    // 2. Assign a value.
    PerformCalculation calc = AddNumbers;
    Person person = new Person();
}

public int AddNumbers(int number1, int number2)
{
    return number1 + number2;
}
See how methods, like AddNumbers, are treated just like objects here? I assign it to my PerformCalculation delegate type. Make sure the signatures are similar.

Using It
// 3. Use it.
int sum = calc(1, 2);
string name = person.GetName();
Remember, your delegate is used to "represent another" method. So when you go to use it, you use it (call it) like a method.

Passing It
Like any object, you can pass it into methods or return it from methods. Here is an example of passing it into a method:
// 4. Pass it.
calc = SubtractNumbers;
string result = CalculateFreeSpace(calc, person);

//...

private int SubtractNumbers(int number1, int number2)
{
    return number1 - number2;
}

private string CalculateFreeSpace(PerformCalculation calc, Person person)
{
    int maxLength = 50;
    int freeSpace = calc(maxLength, person.GetName().Length);
    return string.Format("Free Space Left: {0}", freeSpace);
}
Before I passed as a parameter into the CalculateFreeSpace method, I decided to have it represent a different method with a similar signature.
Pretty interesting, huh? Here, I am injecting customized functionality into the method.
This opens up possibilities to you. You can use this as a way of doing your unit testing. Perhaps the delegate you pass in really calls a SQL Server. So before your unit test calls the method to be tested, you create your delegate to return a hard-coded result instead of calling your SQL Server.

I will be talking more about delegates tomorrow as well.

More Info: MSDN: Delegates

Tuesday, April 22, 2008

Formatting DateTime Strings

The DateTime object has some handy built in methods to format your date like .ToShortDateString() or .ToLongTimeString(). But often you need to combine two formats. Here are some ideas.
string format1 = string.Format("{0} {1}", DateTime.Now.ToShortDateString(), DateTime.Now.ToLongTimeString());
Here, I am just concatenating the output from two methods. There must be an easier way! To get the same exact output, you can customize the format of your ToString() output:
string format2 = DateTime.Now.ToString("M/dd/yyyy h:mm:ss tt");
You could also encapsulate this functionality into an extension method if you use it enough:
public static class DateTimeExtensions
{
    public static string ToShortDateLongTimeString(this DateTime d)
    {
        return d.ToString("M/dd/yyyy h:mm:ss tt");
    }
}
// ...
// To consume this extension method:
string format3 = DateTime.Now.ToShortDateLongTimeString();

More Info: MSDN: DateTime.ToString
More Info: List of ToString Formats

Monday, April 21, 2008

StartsWith, EndsWith

Here are a couple of useful methods that the string class provides. String.StartsWith and String.EndsWith.
List<string> names = new List<string>();
names.Add("Moeykens");
names.Add("Agee");
names.Add("Talbot");
names.Add("major");

foreach (string name in names)
{
    if (name.StartsWith("M", true, null))
        Console.WriteLine(name);
}

foreach (string name in names)
{
    if (name.EndsWith("e"))
        Console.WriteLine(name);
}
The first foreach loop will return:
Moeykens
major
The second parameter for the StartsWith method is set to "true" which tells the class to ignore case.

The second foreach will return:
Agee

More Info: MSDN: String.StartsWith
MSDN: String.EndsWith

Friday, April 18, 2008

SortedList and SortedDictionary Generics

The SortedList and SortedDictionary generic classes are very similar. They are strongly typed at declaration time and as you add items to the collections they become sorted.
SortedList<string, int> list = new SortedList<string, int>();
list.Add("Jake", 2);
list.Add("Rich", 4);
list.Add("Aaron", 1);
list["Mark"] = 3; // Adds entry if not found.

foreach (KeyValuePair<string, int> pair in list)
{
    Console.WriteLine(pair.Value + " - " + pair.Key);
}
The result of the foreach looks like this:
1 - Aaron
2 - Jake
3 - Mark
4 - Rich

The code above can be swapped out with a SortedDictionary with no problems.

One of the main differences between the SortedList and the SortedDictionary is that SortedList also contains an index value in addition to a key and a value for each item in the collection. Therefore it has methods and properties around this feature.
int index = list.IndexOfKey("Aaron");
int index2 = list.IndexOfValue(3);
list.RemoveAt(3);
The SortedDictionary cannot be used in substitution of the SortedList in the code above. Because SortedList has indexes it also comes with additional overhead. So if you do not have the need for the indexes, I would stick with the SortedDictionary.
More Info: MSDN: SortedList and SortedDictionary Collection Types

Thursday, April 17, 2008

Dictionary - Collection

The Dictionary is class that can hold a collection of strongly typed key value pairs.
Dictionary<int, string> dictionary = new Dictionary<int, string>();
dictionary.Add(1, "Mark Moeykens");
dictionary.Add(2, "Jake Agee");
// Will add "Rich Talbot" if indexer (3) not found.
dictionary[3] = "Rich Talbot";

string person = dictionary[3]; // Rich Talbot
In this example I made the key an int and the value a string.

Not all the time will you know if a key exists when you look up a value in your Dictionary. Two ways you can go about trying to get a name:
string name;
if (dictionary.TryGetValue(4, out name))
    name = "Found: " + name;
else
    name = "No name found.";
TryGetValue method returns true if the key is found and puts the found value into the "name" variable in this case.
string name2;
if (dictionary.ContainsKey(4))
    name2 = "Found: " + dictionary[4];
else
    name2 = "No name found.";
This example just checks to see if it exists and then gets the value on a seperate line if true.

More Info: MSDN: Dictionary<TKey, TValue> Generic Class

Wednesday, April 16, 2008

Enum Class

An enum is a constant that contains words to represent numbers basically. For example, your program might refer to days of the week with numbers 1 to 7, but to make your code more readable you can create an enum to show that 1 is equal to "Sunday". Here is an example: Before:
private void DoWork(int today)
{
    if (today == 1  today == 2)
        TakeABreak();
    else
        GetToWork();
}
After:
public enum Day
{
    Sunday = 1,
    Monday = 2,
    Tuesday = 3,
    Wednesday = 4,
    Thursday = 5,
    Friday = 6,
    Saturday = 7
}

private void DoWork(Day today)
{
    if (today == Day.Sunday  today == Day.Saturday)
        TakeABreak();
    else
        GetToWork();
}
But say you have an outside program that refers to days of week by actual names and not numbers, you can still use your enum:
private void DoWork(string today)
{
    if (today == Day.Sunday.ToString() 
        today == Day.Saturday.ToString())
        TakeABreak();
    else
        GetToWork();
}
More Info: MSDN: Enum Class

Tuesday, April 15, 2008

Overloading Constructors

You have a class that you can initialize with different data. The consumer of your class might not have all the data though. You could solve this problem with multiple constructors.
public class Person
{
    private string _firstName;
    private string _lastName;

    public Person (string firstName)
    {
        _firstName = firstName;
    }

    public Person (string firstName, string lastName)
    {
        _firstName = firstName;
        _lastName = lastName;
    }
}
But you will notice you have some repeated code here, where _firstName is getting set to the parameter passed into both constructors. We can minimize duplicate code a couple ways.

One way is to have one constructor call another constructor:
public class Person2
{
    private string _firstName;
    private string _lastName;

    public Person2(string firstName)
        : this(firstName, string.Empty) {}

    public Person2(string firstName, string lastName)
    {
        _firstName = firstName;
        _lastName = lastName;
    }
}
Some people prefer to have all constructors call a single method:
public class Person3
{
    private string _firstName;
    private string _lastName;

    public Person3(string firstName)
    {
        Constructor(firstName, string.Empty);
    }

    public Person3(string firstName, string lastName)
    {
        Constructor(firstName, lastName);
    }

    private void Constructor(string firstName, string lastName)
    {
        _firstName = firstName;
        _lastName = lastName;
    }
}

Monday, April 14, 2008

using Statement

With a using statement, your objects will dispose of themselves once out of scope of the using statement block. For example, you ever open a file or open a connection to a database and then at the end close your connection? The using statement can do this for you.
Before:
SqlConnection conn = null;
SqlCommand cmd = null;

try
{
    conn = new SqlConnection(connString);
    cmd = new SqlCommand(commandString, conn);

    conn.Open();
    cmd.ExecuteNonQuery();
}
finally
{
    if (cmd != null)
        cmd.Dispose();
    if (conn != null)
        conn.Dispose();
}
After:
using (SqlConnection conn = new SqlConnection(connString))
{
    using (SqlCommand cmd = new SqlCommand(commandString, conn))
    {
        conn.Open();
        cmd.ExecuteNonQuery();
    }
}
Can I do this with any object?
In order to use using, the object has to implement IDisposable. Notice the SqlConnection class:

IDisposable only has one method, "Dispose()". The implemented Dispose method on the IDisposable interface will get called as soon as execution leaves the using code block.
This is pretty interesting. Can you think of any of your classes where you have to perform some cleanup when done? You could implement IDisposable and then use your classes in using statements.

More Info: MSDN: using Statement

Sunday, April 13, 2008

Looping Through Your Class

You may want others who use your class to be able to loop through it. To make this possible your class has to use the interface IEnumerable and implement IEnumerable.GetEnumerator() method.
public class Family : IEnumerable
{
    private List<string> familyMembers = new List<string>()
            {
                //Collection Initializer
                "Mother", "Father", "Patty", "Bob"
            };

    public IEnumerator GetEnumerator()
    {
        foreach (string member in familyMembers)
        {
            if (member == "Mother")
                yield return "Claudia";
            else if (member == "Father")
                yield return "Phillip";
            else
                yield return member;
        }
    }
}
In your GetEnumerator function you can customize the way data is returned when a consumer does a foreach on your class.
Family family = new Family();
foreach (string member in family)
{
    Console.WriteLine(member);
}
More Info: MSDN: Iterators

Saturday, April 12, 2008

Using System.Diagnostics.StopWatch

In the old days if wanted to do a quick performance test you could write a test and track the start and end time and see what the difference was between them. Now there is a StopWatch class that can do this for you!
My friend Jake and I were talking about doing quick performance tests on exception handling. We can definitely use this handy class to help out with that.
using System.Diagnostics;

[Test]
public void StringBuilderTest()
{
    Stopwatch watch = new Stopwatch();
    watch.Start();

    StringBuilder sb = new StringBuilder();
    int iterations = 10000000; // 10 million
    for (int i = 0; i < iterations; i++)
    {
        sb.Append(i);
    }

    watch.Stop();
    Console.Write("Elapsed Time: " + watch.Elapsed);
}
More Info: MSDN: Stopwatch Class

Friday, April 11, 2008

Yield Keyword

You use yield to return values many times from one method call. The test below shows how this can be done: (Notice the first line uses a Collection Initializer)
private List<string> Names = new List<string>() { "Mark", "Matt" };

[Test]
public void RunLoopWithYield()
{
    string output = string.Empty;

    foreach (string yieldedValue in ReturnOneNameAtATime())
    {
        output += yieldedValue;
    }

    Assert.AreEqual("Start_Mark_Matt_End", output);
}

private IEnumerable<string> ReturnOneNameAtATime()
{
    // Return this first and then come back.
    yield return "Start_";

    foreach (string name in Names)
    {
        // Return one name at a time.
        yield return name + "_";
    }

    // Return this last but come back one last time
    // to actually exit method.
    yield return "End";
}
See how the path of execution is different with the yield statements:

Thursday, April 10, 2008

String vs. StringBuilder

String type is immutable. Immutable basically means "cannot be changed". Consider the following code:
   1:  string name = "Mark";
   2:  name += " Moeykens";
   3:  name = string.Format("Mr. {0}", name);
On line 1 a string was assigned "Mark". On line 2 "Mark" was thrown away and a new string was created, "Mark Moeykens". On line 3 "Mark Moeykens" was thrown away and a new string, "Mr. Mark Moeykens" was created. Since strings are immutable, a new place in memory has to be created everytime the value changes. StringBuilder manipulates strings much more efficiently. In cases where you have a lot of string manipulation, StringBuilder would be a better candidate.
StringBuilder sb = new StringBuilder();
sb.Append("Mark");
sb.Append(" Moeykens");
sb.Insert(0, "Mr. ");
Notes
  • StringBuilder still outperforms string when concatenating just two strings.
  • There is not much of a difference in time (milliseconds) until you go over about 10,000 concatenations
  • StringBuilder is a good choice for applications that need to scale, like web applications.

More Info: MSDN: Using the StringBuilder Class

Wednesday, April 9, 2008

TableAdapters

TableAdapters allow you to get data from a DataSet. You use DataSets to connect to a database and retrieve table schema information. Then when you want to get the data you use the table's TableAdapter.
TableAdapters are nothing more than classes with methods that you can create visually through a designer. The methods are sql queries.
So if you want to get a populated table you call one of these two premade methods.
MessageTableAdapter adapter = new MessageTableAdapter(); 
Message messageDataTable = adapter.GetData(); 
TableAdapters will:
  • Open a connection.
  • Query for the data.
  • Return the data in the table schema it is attached to.
  • Close the connection.

You can create as many methods as you want on the TableAdapter to:

  • Insert
  • Update
  • Delete
  • Select

More Info: MSDN: TableAdapter Overview

Tuesday, April 8, 2008

Extension Methods

You can write new methods to add to existing .NET classes without having to inherit the class. These can be common functions you always find yourself doing that you wish .NET could do out of the box. For example, doing string.Format on strings.
Before:
string name = "Mark"; 
string message = "Hello, my name is {0}."; 
return string.Format(message, name); 

After:
// ExtensionMethods.cs
public static class StringExtensionMethods
{
    public static string FormatThis(this string s, string arg)
    {
        return string.Format(s, arg);
    }
}

// Code elsewhere
string name = "Mark";
string message = "Hello, my name is {0}.";
return message.FormatThis(name);
Notice:
1. Your extension method and the class it is in has to be static.
2. The first argument is "this", "this" is the actual object you are extending.

More Info: Scott Guthrie: New "Orcas" Language Feature: Extension Methods

Monday, April 7, 2008

Resource Files

A resource file is a sort of container in which you can add things that will get compiled into your dll when you build your project. Once you add an item to the resource file, a static property is created on the resource file so you can access it in your code.
Using a Resource File:
1. Right-click on your project and select Add > New Item... .
2. Select "Resource File" in the dialog box and click OK.
3. Add a string to the resource file.
4. Now you can reference this new string in code like this:
command.CommandText = string.Format(Resource1.PeopleQuery, "'VT'");

More Info: MSDN: Adding and Editing Resources

Sunday, April 6, 2008

Class and Collection Initializers

Initializers allow you to set properties of a class or populate a collection in the same line that you instantiate your class/collection.

Classes
public class Person 
{
     public string First { get; set; }
     public string Last { get; set; } 
}
Before:
Person person = new Person(); 
person.First = "Mark"; 
person.Last = "Moeykens"; 
After:
Person person = new Person(){Last="Moeykens", First="Mark"};
(Notice the properties do not have to be in any order.)

Collections
Before:
List people = new List(); 
people.Add("Moeykens"); 
people.Add("Major"); 
people.Add("Hayek"); 
After:
List<string> people = new List<string>() {"Moeykens", "Major", "Hayek"};
Collection of Classes
Before:
List people = new List(); 
people.Add(new Person() {First="Mark", Last="Moeykens"}); 
people.Add(new Person() {First="Dean", Last="Major"}); 
people.Add(new Person() {First="George", Last="Hayek"}); 
After:
List people = new List() 
{
     new Person() {First="Mark", Last="Moeykens"},
     new Person() {First="Dean", Last="Major"},
     new Person() {First="George", Last="Hayek"} 
}; 
More Info: MSDN: Object and Collection Initializers

Saturday, April 5, 2008

Generics

Generics allows you to make an object a specific type. This allows intellisense to work on the object; which will also do type checking at compile time (meaning it won't build if you are trying to do something like assign an int to a string).

Before:
ArrayList people = new ArrayList();
people.Add("Moeykens");

string person = (string)people[0];
// Note: Without casting to string, you 
// will get error: "Cannot convert source 
// type 'object' to target type 'string'"
After:
List<string> people = new List<string>(); 
people.Add("Moeykens"); 
string person = people[0]; 

Compare the tooltips for each Add method.
Before:

After:


More Info:MSDN: Generics

Friday, April 4, 2008

Anonymous Types

Anonymous types (classes) allow you to create a class with members without actually defining a class first. You saw a small example of this under the var Variable post.

Before:
public class Person() 
{     
     // Auto Implemented Properties
     public string FirstName { get; set; }
     public string LastName { get; set; } 
} 

Person person = new Person(); 
person.FirstName = "Mark"; 
person.LastName = "Moeykens";
After:
var person = new {
                     FirstName="Mark", 
                     LastName="Moeykens"
                 }; 

// The FirstName member will appear in intellisense
string firstName = person.FirstName; 
Notice "FirstName" and "LastName" are being initialized within the braces. This is a new feature of C# 3.0 called Object Initializing. The variable 'person' will also have full intellisense.

More Info: MSDN: Anonymous Types

Thursday, April 3, 2008

Partial Classes

Partial classes allow you to break out a class into multiple pieces, usually this is done in multiple files. Why would you want to do this? Well, have you ever seen a really cluttered class that is about 1,000 lines long? Have you ever opened up a Windows Form that had so many controls and many events on those controls that the code file was incredibly long and you spent a lot of time scrolling?

That is why.

It also allows Microsoft to separate out all their auto-generated code so you never have to see it again.

Before:
// MyClass.cs
public class MyClass 
{
      // Line 1
      public void DoWorkHere() { }

      public void DoWorkThere() { }
      // Line 1,026 
}
After:
// MyClass.DoWorkHere.cs
public partial class MyClass 
{
      // Line 1
      public void DoWorkHere() { }
      // Line 513 
} 

// MyClass.DoWorkThere.cs
public partial class MyClass 
{
      // Line 1
      public void DoWorkThere() { } 
     // Line 513 
}
More Info:MSDN: Partial Classes

Wednesday, April 2, 2008

Nullable Types

Value types (such as int) cannot be made null. This code:
int age = null;
will produce an error that says, Cannot convert source type 'null' to target type 'int'.

Now you can convert value types to a nullable type by using a question mark (?) right after the type declaration:
int? age = null; 
if (age != null) DoSomething(); 
//or 
if (age.HasValue) DoSomething(); 
Nullable types expose a new boolean HasValue property.

Now you don't have to agree upon a "standard" representation of a null condition, invalid value or an uninitialized value for your reference types. Like saying, everytime you see a -1 for this int, it means nothing was returned or that your int has no value.

More Info: MSDN: Nullable Types

Tuesday, April 1, 2008

String.IsNullOrEmpty method

Returns true if the string passed in is null or empty. Otherwise returns false.
Before:
if (name == null || name == string.Empty)) 
{
     return "Please enter a name."; 
}
After:
if (string.IsNullOrEmpty(name)) 
{     
    return "Please enter a name."; 
}
More Info: MSDN: String.IsNullOrEmpty