Learn a Tiny Bit of C# in Seven Days - Day Five

This is part five of the series. Before reading this article, I highly recommend reading the previous parts on learning C#:

Abstract

This article is based on learning basic C# concepts in order to create applications using C# language. 

Introduction

This is the fifth day of learning a tiny bit of C# in 7 days. In this series we will extend our topics try to cover basic of those topics.

What did we learn last time?

In the last article we covered following topics:

  1. Delegates
  2. Enums
  3. Attributes
  4. Generics

Agenda for Day 5

  1. Reflection
  2. Early Binding/ Late Binding
  3. Stringbuilder/ System.String
  4. Var Keyword
  5. Extension Method

    learn

1.1 Reflection

Reflection is the ability to inspect assembly metadata at runtime. It is used to find all types in an assembly.

It can invoke member of the class.

Practical Uses of Reflection

  1. If you are creating an Editor where we want to show metadata of the object by using intelligence.
  2. Invoking private methods for testing.

Sometimes we would like to dump properties, methods and assembly reference to a file probably to show it on a screen.

Let’s try and unleash the Basic concept of Reflection. Let’s switch to visual studio and create a new console application.

console
                                       Figure 1: Creating a new Console Application

While implementing Reflection in your application you need to have two important Namespace:

  • System.Reflection
  • Sytem.Type

These two work together in order to perform Reflection related operations in .NET. Sytem. Reflection namespace contains all the necessary set of classes, interface, properties.

In this demo I will be creating a class library declare its properties, functions and constructor and try to extract all the members of class using Reflection.

  1. Add a new Class Library

    Library
                                                          Figure 2: Creating a new Class Library

    We create our StoreMaster class as shown below:

    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Text;  
    5. using System.Threading.Tasks;  
    6.   
    7. namespace Store  
    8. {  
    9.     //Interface ICreate will have a method called CreateStore which will be implemented by  
    10.     // StoreMaster class to create Store  
    11.     interfaceICreate   
    12.     {  
    13.         void CreateStore();  
    14.   
    15.     }  
    16.   
    17.     publicclassStoreMaster: ICreate  
    18.     {  
    19.   
    20.         publicint storeId  
    21.         {  
    22.             get;  
    23.             set;  
    24.         }  
    25.         publicstring storeName  
    26.         {  
    27.             get;  
    28.             set;  
    29.         }  
    30.         publicstring storeAddress  
    31.         {  
    32.             get;  
    33.             set;  
    34.         }  
    35.   
    36.         publicvoid CreateStore()  
    37.         {  
    38.             //implementation for storeCreation  
    39.             Console.WriteLine("Store Created");  
    40.         }  
    41.   
    42.         publicStoreMaster PrintDetails(int Id)  
    43.         {  
    44.             //sample list of store sample it will come from database  
    45.             List < StoreMaster > listStoreMaster = newList < StoreMaster > () {  
    46.                 newStoreMaster()  
    47.   
    48.                 {  
    49.                     storeId = 1,  
    50.                         storeName = "Kirana",  
    51.                         storeAddress = "Mumbai"  
    52.   
    53.                 },  
    54.   
    55.                 newStoreMaster()  
    56.   
    57.                 {  
    58.                     storeId = 2,  
    59.                         storeName = "Local",  
    60.                         storeAddress = "Dehradun"  
    61.   
    62.                 },  
    63.                 newStoreMaster()  
    64.   
    65.                 {  
    66.                     storeId = 3,  
    67.                         storeName = "Friendz",  
    68.                         storeAddress = "Bangalore"  
    69.   
    70.                 },  
    71.             };  
    72.   
    73.             StoreMaster store = listStoreMaster.Single(str => str.storeId == Id);  
    74.             return store;  
    75.         }  
    76.     }  
    77. }  

    Build the store class and we will see in the Store class library location and store dll has been created and now we remove the store library class from our project. Now with the help of Reflection we will try to fetch all the information of the class using reflection.


    Creation
                                                 Figure 3: Creation of Store.dll





    code
                                           Figure 4: GetType of the Full Name(Namesace.Class)

    You can see that I have removed the Store class library and am trying to access the member and function of class using Reflection.

    Type Properties:
    1. using System;  
    2. using System.Reflection;  
    3.   
    4. namespace Reflection   
    5. {  
    6.     classProgram  
    7.     {  
    8.         staticvoid Main(string[] args)  
    9.         {  
    10.             //loading the whole Assembly  
    11.             var assembly = Assembly.LoadFile(@ "C:\Users\Developer\Documents\visual studio 2015\Reflection\Reflection\Store\bin\Debug\Store.dll");  
    12.             //retrieving the class type where we make use of Type class  
    13.             //It represents type declaration it can be class, interface, array etc.  
    14.             //getType returns the current type of Assembly.  
    15.             var type = assembly.GetType("Store.StoreMaster");  
    16.             //check if type is a class  
    17.             bool classStatus = type.IsClass;  
    18.             Console.WriteLine($ "Is this Type is a Class= {classStatus} ");  
    19.             //check if type is an Interface  
    20.             bool interfaceStatus = type.IsInterface;  
    21.             Console.WriteLine($ "Is this Type is an Interface= {interfaceStatus} ");  
    22.             //check if type is an abstract class  
    23.             bool abstractClass = type.IsAbstract;  
    24.             Console.WriteLine($ "Is this Type is an Abstract Class= {abstractClass} ");  
    25.             Console.ReadLine();  
    26.         }  
    27.     }  
    28. }  
    Output

    output
                                     Figure 5: Displaying Type Is

    You can checkout a whole list of properties of Type class in below url: https://msdn.microsoft.com/en-us/library/system.type(v=vs.110).aspx
    Var Keyword in C#

    Methods: methods in Sytem.Type is used to retrieve the list of methods of the Type. Let’s cover few of them.

    GetProperties: Returns an array of PropertyInfo array.

    run
                                                 Figure 6: PropertyInfo Return Type

    This method returns an array of PropertyInfo as shown in the above diagram. Now once will get all lists of Properties we will loop through all of them and check whether all of them exist in the Class or not.
    1. using System;  
    2. using System.Reflection;  
    3.   
    4. namespace Reflection   
    5. {  
    6.   
    7.     classProgram  
    8.     {  
    9.         staticvoid Main(string[] args)   
    10.         {  
    11.             //loading the whole Assembly  
    12.             var assembly = Assembly.LoadFile(@ "C:\Users\Developer\Documents\visual studio 2015\Reflection\Reflection\Store\bin\Debug\Store.dll");  
    13.             //retrieving the class type where we make use of Type class  
    14.             //It represents type declaration it can be class, interface, array etc.  
    15.             //getType returns the current type of Assembly.  
    16.             var type = assembly.GetType("Store.StoreMaster");  
    17.   
    18.             //retrieving all the class properties  
    19.   
    20.             PropertyInfo[] properties = type.GetProperties();  
    21.             foreach(PropertyInfo property in properties)  
    22.             {  
    23.                 Console.WriteLine(property.Name + " " + property.PropertyType.Name);  
    24.             }  
    25.   
    26.             Console.ReadLine();  
    27.         }  
    28.     }  
    29. }  
    Output:

    output
             Figure 7: Displaying Property Name and PropertyType Name


    We can also retrieve a single property by just using type.getProperty(“specify the property name”).

    Retrieving all Methods using MethodInfo:

    1. using System;  
    2. using System.Reflection;  
    3. usingstatic System.Console;  
    4. namespace Reflection  
    5. {  
    6.     classProgram  
    7.     {  
    8.         staticvoid Main(string[] args)   
    9.         {  
    10.             //loading the whole Assembly  
    11.             var assembly = Assembly.LoadFile(@ "C:\Users\Developer\Documents\visual studio 2015\Reflection\Reflection\Store\bin\Debug\Store.dll");  
    12.             //retrieving the class type where we make use of Type class  
    13.             //It represents type declaration it can be class, interface, array etc.  
    14.             //getType returns the current type of Assembly.  
    15.             var type = assembly.GetType("Store.StoreMaster");  
    16.             WriteLine("retrieving single method by name");  
    17.             MethodInfo method = type.GetMethod("PrintDetails");  
    18.             Console.WriteLine($ "Method name is {method.Name}");  
    19.             //retrieving all the class functions  
    20.             MethodInfo[] methods = type.GetMethods();  
    21.             Console.WriteLine($ "All method present in {type.Name}");  
    22.             foreach(MethodInfo methodInfo in methods)   
    23.             {  
    24.                 Console.WriteLine($ "method Name= {methodInfo.Name}");  
    25.             }  
    26.             Console.ReadLine();  
    27.         }  
    28.     }  
    29. }  
    method
    Figure 8: Displaying list of method Name present in Type

    You will be getting confused why there are so many methods as we have only declared two methods; PrintDetails and CreateStore.

    Get_storeid and set_Storeid are internal methods of property and same as other properties whereas toString(), equals(), getHashCode(), getType(). As we know that .net has base class called object and all are type directly or indirectly inherit from system.object class.

    Let execute printDetails function using reflection.
    1. using System;  
    2. using System.Reflection;  
    3. usingstatic System.Console;  
    4. namespace Reflection   
    5. {  
    6.     classProgram  
    7.     {  
    8.         staticvoid Main(string[] args)   
    9.         {  
    10.             //loading the whole Assembly  
    11.             var assembly = Assembly.LoadFile(@ "C:\Users\Developer\Documents\visual studio 2015\Reflection\Reflection\Store\bin\Debug\Store.dll");  
    12.             //retrieving the class type where we make use of Type class  
    13.             //It represents type declaration it can be class, interface, array etc.  
    14.             //getType returns the current type of Assembly.  
    15.             var type = assembly.GetType("Store.StoreMaster");  
    16.             //calling PrintDetails method of storeMaster class  
    17.             //creating instance of specified type using the constructor (create types of objects locally or remotely)  
    18.             var instance = Activator.CreateInstance(type);  
    19.             //creating parameter for the method  
    20.             object[] parameter = newobject[1];  
    21.             parameter[0] = 1;  
    22.             //retrieving method references  
    23.             MethodInfo method = type.GetMethod("PrintDetails");  
    24.             WriteLine("Calling PrintDetails method");  
    25.             //i have used dynamic because as we don't know the properties at run time they will be retrieved and displayed to the user  
    26.             dynamic typeClass = (object) method.Invoke(instance, parameter);  
    27.             Console.WriteLine(typeClass.storeId);  
    28.             Console.WriteLine(typeClass.storeName);  
    29.             Console.WriteLine(typeClass.storeAddress);  
    30.             Console.ReadLine();  
    31.         }  
    32.     }  
    33. }  

    PrintDetails
                Figure 9: Calling PrintDetails method of storeMaster class

    Now if we want to retrieve constructor we can do the same by following.
    1. WriteLine("retrieving constructor ");  
    2. ConstructorInfo[] constructors = type.GetConstructors();  
    3. foreach(ConstructorInfo constructor in constructors)  
    4. {  
    5.     Console.WriteLine(constructor.ToString());  
    6. }  
    7. Console.ReadLine();  
    Figure 10: Retrieving constructors

    We only default constructor which is automatically created by compiler if we don’t have any parameterized constructor. If we don't provide an overloaded constructor, the compiler will generate a default constructor for us.

    Let’s go in depth and create a Constructor in our class. So for that we need to open our class project and create parameterized constructor as shown below.
    1. public StoreMaster(int id, string name, string address)   
    2. {  
    3.     this.storeId = id;  
    4.     this.storeName = name;  
    5.     this.storeAddress = address;  
    6. }
    And add a function to display the assigned value of properties while creating an instance of this class.
    1. publicvoid PrintStoreValues()  
    2. {  
    3.     Console.WriteLine("The value of StoreId is={0} ,StoreName= {1} ,StoreAddress={2}", storeId, storeName, storeAddress);  
    4.   
    5. }  
    So if we want to how many constructor are there and their type we will first retrieve all the constructorsand then move ahead creating instances of the Type.
    1. using System;  
    2. using System.Reflection;  
    3. namespace Reflection  
    4. {  
    5.     classProgram  
    6.     {  
    7.         staticvoid Main(string[] args)  
    8.         {  
    9.             //loading the whole Assembly  
    10.             var assembly = Assembly.LoadFile(@ "C:\Users\Developer\Documents\visual studio 2015\Reflection\Reflection\Store\bin\Debug\Store.dll");  
    11.             //retrieving the class type where we make use of Type class  
    12.             //It represents type declaration it can be class, interface, array etc.  
    13.             //getType returns the current type of Assembly.  
    14.             var type = assembly.GetType("Store.StoreMaster");  
    15.             //now in order to create instance of the type we need to how many constructor are there  
    16.             ConstructorInfo[] constructors = type.GetConstructors();  
    17.             foreach(ConstructorInfo constructor in constructors)  
    18.             {  
    19.                 Console.WriteLine(constructor.ToString());  
    20.             }  
    21.             Console.ReadLine();  
    22.         }  
    23.     }  
    24. }  

    constructors
             Figure 11: Retrieving parameterized constructors

    We can see there is one parameterized constructor which has three parameters. Now once we know the parameters type of constructor let’s try to invoke the class instance and call PrintStoreValuesmethod.
    1. using System;  
    2. using System.Reflection;  
    3. namespace Reflection  
    4. {  
    5.     classProgram  
    6.     {  
    7.         staticvoid Main(string[] args)  
    8.         {  
    9.             //loading the whole Assembly  
    10.             var assembly = Assembly.LoadFile(@ "C:\Users\Developer\Documents\visual studio 2015\Reflection\Reflection\Store\bin\Debug\Store.dll");  
    11.             //retrieving the class type where we make use of Type class  
    12.             //It represents type declaration it can be class, interface, array etc.  
    13.             //getType returns the current type of Assembly.  
    14.             var type = assembly.GetType("Store.StoreMaster");  
    15.             //creating parameters for the constructor  
    16.             object[] consParameter = newobject[3];  
    17.             consParameter[0] = 1;  
    18.             consParameter[1] = "BigBazaar";  
    19.             consParameter[2] = "Dehradun";  
    20.             //now creating an instance of the Type using Activator  
    21.             var objType = Activator.CreateInstance(type, consParameter);  
    22.             //retrieving method metadata from the type  
    23.             MethodInfo methodToBeCalled = type.GetMethod("PrintStoreValues");  
    24.             //calling PrintStoreValues method and passing the instance of the Type  
    25.             //we have passed null because it takes no parameters  
    26.             methodToBeCalled.Invoke(objType, null);  
    27.             Console.ReadLine();  
    28.         }  
    29.     }  
    30. }  
    Note:

    If you want to see a real life project we can take any IDE eg visual studio.

    I have come across one of my favorite tools called .NET Reflector, IL tool etc. Have a look at  any one of these to see how great these tools are when we want check the class structure, methods, properties of classed we just use in our project. Here is a snapshot of System.web.Mvc dll

    demonstration
    Figure 12: Snapshot of demonstration of ActionResult derived type using IL Spy tool.

    Debugging
    Debugging
    Debugging
                                                    Figure 13: Debugging Snapshots

  2. LateBinding

    Before moving ahead let's first learn about early Binding.

    Early Binding means methods, properties, constructor etc are checked during the compile time, whereas in a Late Binding method, properties and constructors are checked during the runtime with the help of Reflection or Dynamic keyword in c#.

    In late Binding it never checks whether that function or Properties are present or not.
    Let try them practically:


    2.1 Early Binding:

    compile
                                                                Figure 14: Compile time check.

    Intellisense clearly shows us the return type of the method as well as input parameter type for the method as shown below.

    Intelisense
                                               Figure 15: Intelisense for method parameter
    1. using System;  
    2. namespace EarlyBinding   
    3. {  
    4.     classProgram   
    5.     {  
    6.         staticvoid Main(string[] args)  
    7.         {  
    8.             //Here we have the information about the class and its corresponding methods  
    9.             //so we are creating its intance  
    10.             Store store = newStore();  
    11.             string result = store.PrintDetails(1, "RM""Koparkhairne, Mumbai""500701");  
    12.             Console.WriteLine(result);  
    13.             Console.ReadLine();  
    14.         }  
    15.     }  
    16.     publicclassStore  
    17.     {  
    18.         publicstring PrintDetails(int storeId, string storeFullName, string storeFullAddress, string pinCode) {  
    19.             return ("The store id of store Name " + storeFullName + " is " + storeId + " located in " + storeFullAddress + " " + pinCode);  
    20.         }  
    21.     }  
    22. }  
    In early binding hence all the properties, methods, errors, type Mismatches, return values are calculated at compile time itself.

    2.2 LateBinding

    Late Binding is basically performed when we don’t have knowledge of the class which we are consuming or creating instance at compile time. So let’s implement the same.

    Let’s cut the Store class and add a new class library and paste the same in that class build your class and once it’s successfully buildthan remove the class library.

    Library
              Figure 16: Remove Class Library Project from Solution
    1. using System;  
    2. using System.Reflection;  
    3.   
    4. namespace EarlyBinding  
    5. {  
    6.     classProgram   
    7.     {  
    8.         staticvoid Main(string[] args)  
    9.         {  
    10.             //load the assembly from the desired location  
    11.             var assmbly = Assembly.LoadFile(@ "C:\Users\Developer\Documents\visual studio 2015\Reflection\EarlyBinding\Store\bin\Debug\Store.dll");  
    12.             Type type = assmbly.GetType("Store.Store");  
    13.             //creating an instance of the type  
    14.             object storeInstance = Activator.CreateInstance(type);  
    15.             //executing method PrintDetails first get the information of method  
    16.             MethodInfo method = type.GetMethod("PrintDetails");  
    17.             object[] parameter = newobject[4]; //because we have int and string parameters  
    18.             parameter[0] = 1;  
    19.             parameter[1] = "Friendz";  
    20.             parameter[2] = "Mumbai";  
    21.             parameter[3] = "348001";  
    22.             //invoking method and passing the parameters cast to string  
    23.             string result = (String) method.Invoke(storeInstance, parameter);  
    24.             Console.WriteLine(result);  
    25.         }  
    26.     }  
    27.   
    28. }  


    Type
                                           Figure 17: Retrieving Type from the Assembly

    Getting the type of the Class Store.

    method
                                        Figure 18: Retrieved method info with its parameters


    Retrieving methodinfo of PrintDetails

    parameters
                                                    Figure 19:Method parameters

    output
                                           Figure 20:Printing the output from Method invoke.

    The output after execution for function. So we can see how to do Late Binding. We can figure out the late binding drawbacks:

    • No compile time checking
    • Complex structure and lengthy code.
    • It also have performance issue because of loading the external assembly.
    • We should use late binding when we are not aware of the class type.

  3. Stringbuilder/ System.String

    Strings are immutable:

    Let’s walk through the  Immutable what actually it means using a simple demo:
    1. using System;  
    2.   
    3. namespace StringBuilder  
    4. {  
    5.     classProgram  
    6.     {  
    7.         staticvoid Main(string[] args)   
    8.         {  
    9.             Console.WriteLine("Sample System.String");  
    10.             string userString = "Learn";  
    11.             userString += "tiny";  
    12.             userString += "bit of";  
    13.             userString += "bit of c#";  
    14.             userString += "bit of c# in 7 days";  
    15.   
    16.         }  
    17.     }  
    18. }  
    Here we are manipulating the string and adding some text to it. When we try to manipulate the string internally what really happens is that in memory each time we manipulate the string a new copy of userString object is created within heap memory. When string is created for the first time in heap memory the reference variable points towards that allocated memory location once we manipulate the string the reference variable now points towards new manipulated string as shown in the below diagram:


    String
                                                             Figure 21: System.String

    Once we create a new copy of the string the old string still remains in the memory unless and until garbage collector comes and destroy the same from the memory

    So here we learned string is an immutable object which means that once it is created it cannot be changed. Let’s try to unleash this checking whether new objects are getting created or not.
    1. classProgram   
    2. {  
    3.     staticvoid Main(string[] args)  
    4.     {  
    5.         Console.WriteLine("Sample System.String");  
    6.         string userString = string.Empty;  
    7.         for (int i = 0; i <= 10000; i++)   
    8.         {  
    9.             userString += "s";  
    10.         }  
    11.     }  
    Here I have created a simple string and manipulated it till the I count is <= 10000. Microsoft has provided us a great tool called CLRProfiler.

    “CLRProfiler is a free tool from Microsoft to help you diagnose memory issues with your managed app.”
    Source: https://clrprofiler.codeplex.com/
    You can download CLRProfiler from https://clrprofiler.codeplex.com/
    Let start debugging our application.

    • Run CLRProfiler


    clr
    profiler

    Figure 22: Figures Demonstrating CLR Profiler Tool. Step By Step process to evaluate the new creation of string objects

    • Check allocation and call Profile checkbox,

    Profile

    • Click on File => Profile Application,

    Application

    • Now give the path of your application.

    Figure 23: Step By Step process to evaluate the new creation of string objects (Continued).
    debug

    • Select the file
    • CLR Profiler will automatically create the Summary as shown below:

    object

    • Click on Object by Address to check the memory consumption,

    memory
    Figure 24: Demonstrating the Bytes of memory consumed by System.String.

    • We can see 97 percent of the memory is consumed by system.string objects. Once we click on Time Line,

    time line

    We would be able to see the below graph,

    graph
    Figure 25: Creation and destruction of Object by Garbage Collector

    Here when you will see it live you will find new objects are created and destroyed. So the alternate of this problem is StringBuilder.

    StringBuilder string are mutable means no matter how many times you manipulate the string there will be one object created for all of them i.e. same object will be changed all the time when we manipulate the stringBuilder. Unlike string stringBuilder is faster as compared to string. We call append method to add string to our stringBuilder. stringBuilder exists inside System.Text namespace.

    builder
                                                                 Figure 26: String Builder

    So let’s try the same example using stringbuilder as shown below:
    1. classProgram   
    2. {  
    3.     staticvoid Main(string[] args)  
    4.     {  
    5.         Console.WriteLine("Sample System.String");  
    6.         StringBuilder userString = newStringBuilder();  
    7.         for (int i = 0; i <= 10000; i++)   
    8.         {  
    9.             userString.Append("s");  
    10.         }  
    11.     }  
    12. }  
    Figure 26: String Builder CLR Profiler Performance

    Let’s check the performance with CLRProfiler. Perform the same steps as done above in System.String.

    Performance

    Now we can see the memory consumption of StringBuilder.

    memory

    So we can conclude with the outcome i.e. we are going to use StringBuilder when our output is going to change again and again where we will use string when we using constant string. You can do.

  4. Var Keyword

    In this article we will try to focus and unleash the use of Var keyword.

    We have often heard of Var keyword in C#, with emergence of C# 3. New Implicitly typed local variable was introduced. In C# we can declare a variable with var keyword and let the compiler define the datatype from the expression used while initialization.

    Eg. Var name=”saillesh”; //Implicit Declaration indirect

    The C# compiler can conclude or decide that the type of my variable name is “String”.
    i.e the above statement generates the same result as the following statements.

    String name=”saillesh”; //Explicit Declaration direct declaration
    This means what type of data type we want to assign to name variable.

    In the Var keyword datatype the compiler at the compile time looks at the right hand side data type and creates the desired data type to the variable. As in example of Var keyword the compiler will assign the string data type to the name variable.

    In single one word terminology we can say that:

    “Var keyword is an Implicit or Indirect way of defining data type”.
    By looking at the right hand side data the datatype is assigned to the var variable during the generation of IL code.
    i.e. var keyword defines data type statically not dynamically.Let’s take a practical example of the same,

    1. namespace Var  
    2. {  
    3.     classProgram  
    4.     {  
    5.         staticvoid Main(string[] args)  
    6.         {  
    7.             //declaration of var keyword   
    8.             var value = 1; //assigned a integer value  
    9.             value = "saillesh"//trying to add string value  
    10.         }  
    11.     }  
    12. }  
    If try to build it we face an error as shown below:

    error
    Figure 27: Error specifying strongly typed Explicit Declaration

    error
    Figure 28: Error specifying strongly typed Explicit Declaration

    So we can see that the error is shown during the compile time not during the runtime.Now once I try to check the data type of the value, it displays the data type as shown below,

    code
    Figure 29: strongly typed variable of type Int

    We can do the same using Type keyword in C# as shown below:
    1. namespace Var  
    2. {  
    3.     classProgram  
    4.     {  
    5.         staticvoid Main(string[] args)  
    6.         {  
    7.             //declaration of var keyword   
    8.             var value = 1; //assigned a integer value  
    9.   
    10.             Type valueType = value.GetType();  
    11.             Console.WriteLine("value if of datatype " + valueType.ToString());  
    12.             Console.WriteLine();  
    13.   
    14.   
    15.         }  
    16.   
    17.     }  
    18. }  

    Displaying
                            Figure 30: Displaying the data typeof Type

    So just to confirm the same, let’s open this application in ILDASM, I declare some more var variable and assign other datatypes to the variable and then see how var keyword is statically defined during run time.
    1. namespace Var  
    2. {  
    3.     classProgram   
    4.     {  
    5.         staticvoid Main(string[] args)  
    6.         {  
    7.             //declaration of var keyword   
    8.             var value = 1; //assigned a integer value  
    9.             var name = "Nishant Negi";  
    10.             var isMale = true;  
    11.             Console.ReadLine();  
    12.             //Type valueType = value.GetType();  
    13.             //Console.WriteLine("value if of datatype "+valueType.ToString());  
    14.             //Console.ReadLine();  
    15.   
    16.         }  
    17.   
    18.     }  
    19. }  
    Open ILDASM

    Step 1:

    Go to start got to Visual Studio and search for Developer Command Prompt .

    Run the Developer Command Prompt and type ILDASM as shown below:

    cmd

    ILDASM will open as shown below:

    ILDASM

    Step 2: Go to your project root directory copy the path of .exe file as shown below:

    path

    Copy the address bar and click on File option in ILDASM.

    ILDASM

    Click on Open and paste the desired location of your Application.

    Application

    And open the same in ILDASM.

    main

    Double click on Main Intermediate Language code will appear.

    find

    Now we can see very clearly that these variables are local variables and are of type:

    • value => int32
    • name => string
    • isMAle =>bool


    So we can say that the var type keyword is statically defined.

    There are few restrictions of Var keyword implicit typed local variables:

    • We must initialize the variable
    If we try to declare Implicit type variable without initialization it give us the compile time error.
    1. classProgram   
    2. {  
    3.     staticvoid Main(string[] args)   
    4.     {  
    5.         var name;  
    6.     }  
    7.   
    8. }  


    code
    Figure 31: Implicit type variable without initialization

    • Var keyword cannot be null,
    1. classProgram   
    2. {  
    3.     staticvoid Main(string[] args)  
    4.     {  
    5.         var name = null;  
    6.     }  
    7.   
    8. }  

    code
                         Figure 32: Var keyword cannot

    • You cannot use object or collection initializers:
    1. classProgram   
    2. {  
    3.     staticvoid Main(string[] args)  
    4.     {  
    5.         var array =   
    6.         { 1, 3, 4, 5 };  
    7.     }  
    8. }  
    code
    Figure 33: Error demonstrating we cannot use object or collection initializers

    1. namespace Var  
    2. {  
    3.     classProgram  
    4.     {  
    5.         staticvoid Main(string[] args)  
    6.         {  
    7.             var value = 1;  
    8.             var name = "Saillesh";  
    9.             var array = newint[]   
    10.             {  
    11.                 1,  
    12.                 3,  
    13.                 4,  
    14.                 5,  
    15.                 6  
    16.             };  
    17.             Console.WriteLine(value);  
    18.             Console.WriteLine(name);  
    19.             foreach(int i in array)   
    20.             {  
    21.                 Console.WriteLine(i);  
    22.             }  
    23.             Console.ReadLine();  
    24.         }  
    25.   
    26.     }  
    27. }  
    Output:

    output
    Figure 33: defining Collection of type int and other var declaration

    So now what is benefit of Var keyword and what scenarios it‘s useful.

    4.1 Object Initializers

    As we follow OOPs principle likes Class, Object etc. We have to do a lot of Object Initialization as shown below:
    1. publicclassCustomer  
    2. {  
    3.     privatestring _customerName;  
    4.   
    5.     publicstring customerName  
    6.     {  
    7.         get;  
    8.         set;  
    9.     }  
    10.   
    11.     privatestring _customerAddress;  
    12.     publicstring customerAddress  
    13.     {  
    14.         get;  
    15.         set;  
    16.     }  
    17.   
    18. }  
    When we instantiate this class we normally write code,
    1. staticvoid Main(string[] args)   
    2. {  
    3.     Customer objCustomer = newCustomer();  
    4.     objCustomer.customerName = "Saillesh Pawar";  
    5.     objCustomer.customerAddress = "Mumbai";  
    6. }  
    7. Or  
    8. staticvoid Main(string[] args)   
    9. {  
    10.     Customer objCustomer = newCustomer()  
    11.     {  
    12.         customerName = "Saillesh Pawar",  
    13.             customerAddress = "Mumbai"  
    14.     };  
    15. }  
    16. Or we can do the same using Var keyword  
    17.   
    18. var objCustomer = newCustomer()   
    19. {  
    20.     customerName = "Saillesh Pawar",  
    21.         customerAddress = "Mumbai"  
    22. };  
    4.2 Initializing Collections

    Let’s take an example of a generic list as shown below,
    1. List < string > objstringList = newList < string > ();  
    2. using System;  
    3. using System.Collections.Generic;  
    4. using System.Linq;  
    5. using System.Text;  
    6. using System.Threading.Tasks;  
    7.   
    8. namespace Var  
    9. {  
    10.     publicclassAuthor  
    11.     {  
    12.         string _author;  
    13.         List < string > _articles = newList < string > ();  
    14.         publicstring author  
    15.         {  
    16.             get  
    17.             {  
    18.                 return _author;  
    19.             }  
    20.             set   
    21.             {  
    22.                 _author = value;  
    23.             }  
    24.         }  
    25.   
    26.         publicList < string > articles   
    27.         {  
    28.             get  
    29.             {  
    30.                 return _articles;  
    31.             }  
    32.             set   
    33.             {  
    34.                 _articles = value;  
    35.             }  
    36.         }  
    37.   
    38.     }  
    39.   
    40.   
    41.     classProgram  
    42.     {  
    43.         staticvoid Main(string[] args)   
    44.         {  
    45.             List < Author > authorList = newList < Author > ();  
    46.             Author objAuthor = newAuthor();  
    47.             objAuthor.author = "Saillesh Pawar";  
    48.             objAuthor.articles.Add("Learn C# day 1");  
    49.             objAuthor.articles.Add("Learn C# day 2");  
    50.             objAuthor.articles.Add("Learn C# day 3");  
    51.             objAuthor.articles.Add("Var keyword");  
    52.             authorList.Add(objAuthor);  
    53.   
    54.             Author objAuthor2 = newAuthor();  
    55.             objAuthor2.author = "Nishant Negi";  
    56.             objAuthor2.articles.Add("Essence of Life");  
    57.             objAuthor2.articles.Add("Serve your Nation");  
    58.             objAuthor2.articles.Add("My life");  
    59.             objAuthor2.articles.Add("Enroute to Ladakh");  
    60.             authorList.Add(objAuthor2);  
    61.   
    62.             Console.WriteLine(objAuthor.author + " Articles Published \n" + objAuthor.articles[0] + "\n" + objAuthor.articles[1]);  
    63.             Console.WriteLine(objAuthor2.author + " Articles Published \n" + objAuthor2.articles[0] + "\n" + objAuthor2.articles[1]);  
    64.             Console.ReadLine();  
    65.         }  
    66.   
    67.   
    68.     }  
    69. }  
    Now same can be done with less amount of code using Var.
    1. using System;  
    2. using System.Collections.Generic;  
    3.   
    4. namespace Var  
    5. {  
    6.     publicclassAuthor   
    7.     {  
    8.         string _author;  
    9.         List < string > _articles = newList < string > ();  
    10.         publicstring author   
    11.         {  
    12.             get   
    13.             {  
    14.                 return _author;  
    15.             }  
    16.             set  
    17.             {  
    18.                 _author = value;  
    19.             }  
    20.         }  
    21.   
    22.         publicList < string > articles   
    23.         {  
    24.             get   
    25.             {  
    26.                 return _articles;  
    27.             }  
    28.             set  
    29.             {  
    30.                 _articles = value;  
    31.             }  
    32.         }  
    33.     }  
    34.     classProgram  
    35.     {  
    36.         staticvoid Main(string[] args)   
    37.         {  
    38.             var autorList = newList < Author > ()   
    39.             {  
    40.                 newAuthor   
    41.                 {  
    42.                     author = "Saillesh Pawar",  
    43.                         articles =   
    44.                         {  
    45.                             "Learn Tiny bit of c# day1",  
    46.                             "Learn tiny bit of C# day2"  
    47.                         }  
    48.                 },  
    49.                 newAuthor  
    50.                 {  
    51.                     author = "Nishant Negi",  
    52.                         articles =  
    53.                         {  
    54.                             "Enjoy the life",  
    55.                             "Enroute to Ladakh"  
    56.                         }  
    57.                 }  
    58.             };  
    59.             //Diplaying 1st author and his/her articles  
    60.             Console.WriteLine("Author name " + autorList[0].author + "Articles Published in 2015 \n 1." + autorList[0].articles[0] + " \n 2." + autorList[0].articles[1]);  
    61.   
    62.             //Diplaying 2nd author and his/her articles  
    63.             Console.WriteLine("Author name " + autorList[1].author + "Articles Published in 2015 \n 1." + autorList[0].articles[1] + " \n 2." + autorList[0].articles[1]);  
    64.             Console.ReadLine();  
    65.         }  
    66.   
    67.   
    68.     }  
    69. }  

    4.3 Linq with Anonymous Types

    I will be covering linq in depth in upcoming articles. Anonymous Types: The C# can create an Anonymous type by using the properties in an object initializer.

    Eg:
    1. var obj = new  
    2. {  
    3.     Name = "saillesh",  
    4.         Address = "Mumbai"  
    5.   
    6.   
    7. };  
    8. Console.WriteLine("Name= {0} , Address={1}", obj.Name, obj.Address);  
    By this the compiler creates an Anonymous type and declares the properties as specified in the object initializer.

    Sometimes we need Anonymous type when we are working with linq, example there are two classes and you are joining them with linq to sql. In order to fetch the value to strongly typed propertiesyou need a class that can hold the records retrieved by the Linq. Well that’s a whole lot of work, you can do the same without creating a class with the help of Var keyword as shown below:
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Text;  
    5. using System.Threading.Tasks;  
    6. using System.Xml.Linq;  
    7.   
    8. namespace Anonymous   
    9. {  
    10.     publicclassMeetingMaster   
    11.     {  
    12.         publicint MOMId   
    13.         {  
    14.             get;  
    15.             set;  
    16.         }  
    17.         publicint SegmentId  
    18.         {  
    19.             get;  
    20.             set;  
    21.         }  
    22.         publicint MeetingNameId  
    23.         {  
    24.             get;  
    25.             set;  
    26.         }  
    27.         publicstring Description  
    28.         {  
    29.             get;  
    30.             set;  
    31.         }  
    32.   
    33.     }  
    34.     publicclassMeetingNameMaster   
    35.     {  
    36.         publicint Id  
    37.         {  
    38.             get;  
    39.             set;  
    40.         }  
    41.         publicstring MeetingName  
    42.         {  
    43.             get;  
    44.             set;  
    45.         }  
    46.     }  
    47.   
    48.   
    49.     classProgram  
    50.     {  
    51.         staticvoid Main(string[] args)  
    52.         {  
    53.             var meetingList = newList < MeetingNameMaster >   
    54.                 {  
    55.                 newMeetingNameMaster  
    56.                 {  
    57.                     Id = 1,  
    58.                         MeetingName = "RMS"  
    59.                 },  
    60.                 newMeetingNameMaster  
    61.                 {  
    62.                     Id = 2,  
    63.                         MeetingName = "Functional"  
    64.                 },  
    65.                 newMeetingNameMaster  
    66.                 {  
    67.                     Id = 3,  
    68.                         MeetingName = "Hr"  
    69.                 }  
    70.   
    71.             };  
    72.   
    73.             var meetingMaster = newList < MeetingMaster >  
    74.                 {  
    75.                 newMeetingMaster  
    76.                 {  
    77.                     MOMId = 1,  
    78.                         MeetingNameId = 1,  
    79.                         Description = "RMS Funtional covered",  
    80.                         SegmentId = 1  
    81.                 },  
    82.                 newMeetingMaster  
    83.                 {  
    84.                     MOMId = 2,  
    85.                         MeetingNameId = 1,  
    86.                         Description = "Functional Agenda Covered"  
    87.   
    88.                 },  
    89.                 newMeetingMaster  
    90.                 {  
    91.   
    92.                     MOMId = 3,  
    93.                         MeetingNameId = 1,  
    94.                         Description = "Rms functional covered responsibility taken by saillesh pawar",  
    95.                         SegmentId = 1  
    96.   
    97.                 }  
    98.             };  
    99.   
    100.             var rmsMeetingCommenced = (from mtnMaster in meetingMaster join meetings in meetingList on mtnMaster.MeetingNameId equals meetings.Id selectnew {  
    101.   
    102.                 MOMId = mtnMaster.MOMId,  
    103.                     Desciption = mtnMaster.Description,  
    104.                     MeetingName = meetings.MeetingName  
    105.             }).ToList();  
    106.   
    107.   
    108.   
    109.   
    110.             foreach(var i in rmsMeetingCommenced)  
    111.             {  
    112.                 Console.WriteLine("The MOM id is {0} \n MeetingId is {1} \n Meeting Description is={2} \n MeetingName is ={3}", i.MOMId, i.MeetingName, i.Desciption, i.MeetingName);  
    113.   
    114.             }  
    115.   
    116.             Console.ReadLine();  
    117.   
    118.   
    119.   
    120.   
    121.         }  
    122.     }  
    123. }  
  5. Extension Method

    We can create an Extension method within a Static class within a static method. The first parameter of an extension class must be keyword this.

    Eg:
    1. using System;  
    2.   
    3. namespace ConsoleApplication3   
    4. {  
    5.     publicstaticclassMyClass   
    6.     {  
    7.   
    8.         publicstaticint Square(thisint Number)  
    9.         {  
    10.             return (Number * Number);  
    11.         }  
    12.   
    13.     }  
    14.   
    15.   
    16.     classProgram  
    17.     {  
    18.         staticvoid Main(string[] args)   
    19.         {  
    20.   
    21.             Console.WriteLine("Enter the Number");  
    22.             int Number = Convert.ToInt32(Console.ReadLine());  
    23.             int squareResult = Number.Square();  
    24.             //We can call the method as it is instance member  
    25.             Console.WriteLine("The square of the number is " + squareResult);  
    26.             Console.ReadLine();  
    27.   
    28.         }  
    29.     }  
    30. }  
    Output:

    output
             Figure 34: Calling Extension Method

    We can do the same without extension method:
    1. int squareResult = MyClass.Square(Number);  

Read more articles on C#:

Up Next
    Ebook Download
    View all
    Learn
    View all