Sunday, November 25, 2012

Two Ways of Initializing a New Object in C#

Recently I posted a question about the different ways one can initialize an object in a C# class. I generally use EXAMPLE 1 below. Resharper suggests I use EXAMPLE 2. EXAMPLE 1 is more intuitive to me (since it is want I always use). However my friend FC pointed out he prefers to "choose a syntax that directly associates the data with the name of its field, rather than relying on the order of the arguments, wherein various perils are wrought", meaning Example 2. I find this argument quite compelling.
My amigo BS has a very nice explanation "The first is required if you need those values for processing during the initialization of your object." This is corroborated in the linked MSDN article at the bottom. BS goes on to say: EXAMPLE 1 "can also be used as a way to force anyone creating the object to always provide those values. The second is useful for things like Data Contract objects where you need a parameter-less constructor for serialization and to assign values directly to its properties in one step. The key difference is values are assigned after construction in the second example."

Even
though my tests tend not to have the serialization requirements facilitated by EXAMPLE 2 I will consider switching course for the sole value stated by FC.
EXAMPLE 1
public static void Main()
{
     StudentName student1 = new StudentName("Marcus", "Deatonus");
...
}
EXAMPLE 2
public static void Main()
{
     StudentName student1 = new StudentName
       {
          FirstName = "Chris",
          LastName = "Bellcamp"
       };
...
}
REFERENCES
http://msdn.microsoft.com/en-us/library/vstudio/bb397680.aspx

No comments:

Post a Comment