神刀安全网

Learna 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
    Learna Tiny Bit of C# in Seven Days - Day Five

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.

Learna Tiny Bit of C# in Seven Days - Day Five

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

    Learna Tiny Bit of C# in Seven Days - Day Five                                                       Figure 2:  Creating a new Class Library
    We create our StoreMaster class as shown below:

    using System;   using System.Collections.Generic;   using System.Linq;   using System.Text;   using System.Threading.Tasks;      namespace Store   {       //Interface ICreate will have a method called CreateStore which will be implemented by       // StoreMaster class to create Store       interfaceICreate        {           void CreateStore();          }          publicclassStoreMaster: ICreate       {              publicint storeId           {               get;               set;           }           publicstring storeName           {               get;               set;           }           publicstring storeAddress           {               get;               set;           }              publicvoid CreateStore()           {               //implementation for storeCreation               Console.WriteLine("Store Created");           }              publicStoreMaster PrintDetails(int Id)           {               //sample list of store sample it will come from database               List < StoreMaster > listStoreMaster = newList < StoreMaster > () {                   newStoreMaster()                      {                       storeId = 1,                           storeName = "Kirana",                           storeAddress = "Mumbai"                      },                      newStoreMaster()                      {                       storeId = 2,                           storeName = "Local",                           storeAddress = "Dehradun"                      },                   newStoreMaster()                      {                       storeId = 3,                           storeName = "Friendz",                           storeAddress = "Bangalore"                      },               };                  StoreMaster store = listStoreMaster.Single(str => str.storeId == Id);               return store;           }       }   }   

    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.
    Learna Tiny Bit of C# in Seven Days - Day Five                                              Figure 3:  Creation of Store.dll
    Learna Tiny Bit of C# in Seven Days - Day Five                                        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:

    using System;   using System.Reflection;      namespace Reflection    {       classProgram       {           staticvoid Main(string[] args)           {               //loading the whole Assembly               var assembly = Assembly.LoadFile(@ "C:/Users/Developer/Documents/visual studio 2015/Reflection/Reflection/Store/bin/Debug/Store.dll");               //retrieving the class type where we make use of Type class               //It represents type declaration it can be class, interface, array etc.               //getType returns the current type of Assembly.               var type = assembly.GetType("Store.StoreMaster");               //check if type is a class               bool classStatus = type.IsClass;               Console.WriteLine($ "Is this Type is a Class= {classStatus} ");               //check if type is an Interface               bool interfaceStatus = type.IsInterface;               Console.WriteLine($ "Is this Type is an Interface= {interfaceStatus} ");               //check if type is an abstract class               bool abstractClass = type.IsAbstract;               Console.WriteLine($ "Is this Type is an Abstract Class= {abstractClass} ");               Console.ReadLine();           }       }   }   

    Output
    Learna Tiny Bit of C# in Seven Days - Day Five                                  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.
    Learna Tiny Bit of C# in Seven Days - Day Five                                              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.

    using System;   using System.Reflection;      namespace Reflection    {          classProgram       {           staticvoid Main(string[] args)            {               //loading the whole Assembly               var assembly = Assembly.LoadFile(@ "C:/Users/Developer/Documents/visual studio 2015/Reflection/Reflection/Store/bin/Debug/Store.dll");               //retrieving the class type where we make use of Type class               //It represents type declaration it can be class, interface, array etc.               //getType returns the current type of Assembly.               var type = assembly.GetType("Store.StoreMaster");                  //retrieving all the class properties                  PropertyInfo[] properties = type.GetProperties();               foreach(PropertyInfo property in properties)               {                   Console.WriteLine(property.Name + " " + property.PropertyType.Name);               }                  Console.ReadLine();           }       }   }   

    Output:
    Learna Tiny Bit of C# in Seven Days - Day Five          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:

    using System;   using System.Reflection;   usingstatic System.Console;   namespace Reflection   {       classProgram       {           staticvoid Main(string[] args)            {               //loading the whole Assembly               var assembly = Assembly.LoadFile(@ "C:/Users/Developer/Documents/visual studio 2015/Reflection/Reflection/Store/bin/Debug/Store.dll");               //retrieving the class type where we make use of Type class               //It represents type declaration it can be class, interface, array etc.               //getType returns the current type of Assembly.               var type = assembly.GetType("Store.StoreMaster");               WriteLine("retrieving single method by name");               MethodInfo method = type.GetMethod("PrintDetails");               Console.WriteLine($ "Method name is {method.Name}");               //retrieving all the class functions               MethodInfo[] methods = type.GetMethods();               Console.WriteLine($ "All method present in {type.Name}");               foreach(MethodInfo methodInfo in methods)                {                   Console.WriteLine($ "method Name= {methodInfo.Name}");               }               Console.ReadLine();           }       }   }   

    Learna Tiny Bit of C# in Seven Days - Day Five 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.

    using System;   using System.Reflection;   usingstatic System.Console;   namespace Reflection    {       classProgram       {           staticvoid Main(string[] args)            {               //loading the whole Assembly               var assembly = Assembly.LoadFile(@ "C:/Users/Developer/Documents/visual studio 2015/Reflection/Reflection/Store/bin/Debug/Store.dll");               //retrieving the class type where we make use of Type class               //It represents type declaration it can be class, interface, array etc.               //getType returns the current type of Assembly.               var type = assembly.GetType("Store.StoreMaster");               //calling PrintDetails method of storeMaster class               //creating instance of specified type using the constructor (create types of objects locally or remotely)               var instance = Activator.CreateInstance(type);               //creating parameter for the method               object[] parameter = newobject[1];               parameter[0] = 1;               //retrieving method references               MethodInfo method = type.GetMethod("PrintDetails");               WriteLine("Calling PrintDetails method");               //i have used dynamic because as we don't know the properties at run time they will be retrieved and displayed to the user               dynamic typeClass = (object) method.Invoke(instance, parameter);               Console.WriteLine(typeClass.storeId);               Console.WriteLine(typeClass.storeName);               Console.WriteLine(typeClass.storeAddress);               Console.ReadLine();           }       }   }   

    Learna Tiny Bit of C# in Seven Days - Day Five             Figure 9: Calling PrintDetails method of storeMaster class
    Now if we want to retrieve constructor we can do the same by following.

    WriteLine("retrieving constructor ");   ConstructorInfo[] constructors = type.GetConstructors();   foreach(ConstructorInfo constructor in constructors)   {       Console.WriteLine(constructor.ToString());   }   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.

    public StoreMaster(int id, string name, string address)    {       this.storeId = id;       this.storeName = name;       this.storeAddress = address;   } 

    And add a function to display the assigned value of properties while creating an instance of this class.

    publicvoid PrintStoreValues()   {       Console.WriteLine("The value of StoreId is={0} ,StoreName= {1} ,StoreAddress={2}", storeId, storeName, storeAddress);      }   

    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.

    using System;   using System.Reflection;   namespace Reflection   {       classProgram       {           staticvoid Main(string[] args)           {               //loading the whole Assembly               var assembly = Assembly.LoadFile(@ "C:/Users/Developer/Documents/visual studio 2015/Reflection/Reflection/Store/bin/Debug/Store.dll");               //retrieving the class type where we make use of Type class               //It represents type declaration it can be class, interface, array etc.               //getType returns the current type of Assembly.               var type = assembly.GetType("Store.StoreMaster");               //now in order to create instance of the type we need to how many constructor are there               ConstructorInfo[] constructors = type.GetConstructors();               foreach(ConstructorInfo constructor in constructors)               {                   Console.WriteLine(constructor.ToString());               }               Console.ReadLine();           }       }   }   

    Learna Tiny Bit of C# in Seven Days - Day Five          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.

    using System;   using System.Reflection;   namespace Reflection   {       classProgram       {           staticvoid Main(string[] args)           {               //loading the whole Assembly               var assembly = Assembly.LoadFile(@ "C:/Users/Developer/Documents/visual studio 2015/Reflection/Reflection/Store/bin/Debug/Store.dll");               //retrieving the class type where we make use of Type class               //It represents type declaration it can be class, interface, array etc.               //getType returns the current type of Assembly.               var type = assembly.GetType("Store.StoreMaster");               //creating parameters for the constructor               object[] consParameter = newobject[3];               consParameter[0] = 1;               consParameter[1] = "BigBazaar";               consParameter[2] = "Dehradun";               //now creating an instance of the Type using Activator               var objType = Activator.CreateInstance(type, consParameter);               //retrieving method metadata from the type               MethodInfo methodToBeCalled = type.GetMethod("PrintStoreValues");               //calling PrintStoreValues method and passing the instance of the Type               //we have passed null because it takes no parameters               methodToBeCalled.Invoke(objType, null);               Console.ReadLine();           }       }   }   

    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
    Learna Tiny Bit of C# in Seven Days - Day Five Figure 12:  Snapshot of demonstration of ActionResult derived type using IL Spy tool.
    Learna Tiny Bit of C# in Seven Days - Day Five Learna Tiny Bit of C# in Seven Days - Day Five Learna Tiny Bit of C# in Seven Days - Day Five                                                 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:

    Learna Tiny Bit of C# in Seven Days - Day Five                                                             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.
    Learna Tiny Bit of C# in Seven Days - Day Five                                            Figure 15:  Intelisense for method parameter

    using System;   namespace EarlyBinding    {       classProgram        {           staticvoid Main(string[] args)           {               //Here we have the information about the class and its corresponding methods               //so we are creating its intance               Store store = newStore();               string result = store.PrintDetails(1, "RM", "Koparkhairne, Mumbai", "500701");               Console.WriteLine(result);               Console.ReadLine();           }       }       publicclassStore       {           publicstring PrintDetails(int storeId, string storeFullName, string storeFullAddress, string pinCode) {               return ("The store id of store Name " + storeFullName + " is " + storeId + " located in " + storeFullAddress + " " + pinCode);           }       }   }   

    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.
    Learna Tiny Bit of C# in Seven Days - Day Five           Figure 16:  Remove Class Library Project from Solution

    using System;   using System.Reflection;      namespace EarlyBinding   {       classProgram        {           staticvoid Main(string[] args)           {               //load the assembly from the desired location               var assmbly = Assembly.LoadFile(@ "C:/Users/Developer/Documents/visual studio 2015/Reflection/EarlyBinding/Store/bin/Debug/Store.dll");               Type type = assmbly.GetType("Store.Store");               //creating an instance of the type               object storeInstance = Activator.CreateInstance(type);               //executing method PrintDetails first get the information of method               MethodInfo method = type.GetMethod("PrintDetails");               object[] parameter = newobject[4]; //because we have int and string parameters               parameter[0] = 1;               parameter[1] = "Friendz";               parameter[2] = "Mumbai";               parameter[3] = "348001";               //invoking method and passing the parameters cast to string               string result = (String) method.Invoke(storeInstance, parameter);               Console.WriteLine(result);           }       }      }   

    Learna Tiny Bit of C# in Seven Days - Day Five                                        Figure 17:  Retrieving Type from the Assembly
    Getting the type of the Class Store.
    Learna Tiny Bit of C# in Seven Days - Day Five                                     Figure 18:  Retrieved method info with its parameters
    Retrieving methodinfo of PrintDetails
    Learna Tiny Bit of C# in Seven Days - Day Five                                                 Figure 19: Method parameters
    Learna Tiny Bit of C# in Seven Days - Day Five                                        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:

    using System;      namespace StringBuilder   {       classProgram       {           staticvoid Main(string[] args)            {               Console.WriteLine("Sample System.String");               string userString = "Learn";               userString += "tiny";               userString += "bit of";               userString += "bit of c#";               userString += "bit of c# in 7 days";              }       }   }   

    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:
    Learna Tiny Bit of C# in Seven Days - Day Five                                                          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.

    classProgram    {       staticvoid Main(string[] args)       {           Console.WriteLine("Sample System.String");           string userString = string.Empty;           for (int i = 0; i <= 10000; i++)            {               userString += "s";           }       }   

    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
    Learna Tiny Bit of C# in Seven Days - Day Five Learna Tiny Bit of C# in Seven Days - Day Five 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,
    Learna Tiny Bit of C# in Seven Days - Day Five • Click on File => Profile Application,
    Learna Tiny Bit of C# in Seven Days - Day Five • Now give the path of your application.
    Figure 23:  Step By Step process to evaluate the new creation of string objects (Continued).
    Learna Tiny Bit of C# in Seven Days - Day Five • Select the file
    • CLR Profiler will automatically create the Summary as shown below:
    Learna Tiny Bit of C# in Seven Days - Day Five • Click on Object by Address to check the memory consumption,
    Learna Tiny Bit of C# in Seven Days - Day Five 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,
    Learna Tiny Bit of C# in Seven Days - Day Five We would be able to see the below graph,
    Learna Tiny Bit of C# in Seven Days - Day Five 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.
    Learna Tiny Bit of C# in Seven Days - Day Five                                                              Figure 26:  String Builder
    So let’s try the same example using stringbuilder as shown below:

    classProgram    {       staticvoid Main(string[] args)       {           Console.WriteLine("Sample System.String");           StringBuilder userString = newStringBuilder();           for (int i = 0; i <= 10000; i++)            {               userString.Append("s");           }       }   }   

    Figure 26: String Builder CLR Profiler Performance
    Let’s check the performance with CLRProfiler. Perform the same steps as done above in System.String.
    Learna Tiny Bit of C# in Seven Days - Day Five Now we can see the memory consumption of StringBuilder.
    Learna Tiny Bit of C# in Seven Days - Day Five 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,

    namespace Var   {       classProgram       {           staticvoid Main(string[] args)           {               //declaration of var keyword                var value = 1; //assigned a integer value               value = "saillesh"; //trying to add string value           }       }   }   

    If try to build it we face an error as shown below:
    Learna Tiny Bit of C# in Seven Days - Day Five Figure 27:  Error specifying strongly typed Explicit Declaration
    Learna Tiny Bit of C# in Seven Days - Day Five 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,
    Learna Tiny Bit of C# in Seven Days - Day Five Figure 29:  strongly typed variable of type Int
    We can do the same using Type keyword in C# as shown below:

    namespace Var   {       classProgram       {           staticvoid Main(string[] args)           {               //declaration of var keyword                var value = 1; //assigned a integer value                  Type valueType = value.GetType();               Console.WriteLine("value if of datatype " + valueType.ToString());               Console.WriteLine();                 }          }   }   

    Learna Tiny Bit of C# in Seven Days - Day Five                         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.

    namespace Var   {       classProgram        {           staticvoid Main(string[] args)           {               //declaration of var keyword                var value = 1; //assigned a integer value               var name = "Nishant Negi";               var isMale = true;               Console.ReadLine();               //Type valueType = value.GetType();               //Console.WriteLine("value if of datatype "+valueType.ToString());               //Console.ReadLine();              }          }   }   

    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:
    Learna Tiny Bit of C# in Seven Days - Day Five ILDASM will open as shown below:
    Learna Tiny Bit of C# in Seven Days - Day Five Step 2: Go to your project root directory copy the path of .exe file as shown below:
    Learna Tiny Bit of C# in Seven Days - Day Five Copy the address bar and click on File option in ILDASM.
    Learna Tiny Bit of C# in Seven Days - Day Five Click on Open and paste the desired location of your Application.
    Learna Tiny Bit of C# in Seven Days - Day Five And open the same in ILDASM.
    Learna Tiny Bit of C# in Seven Days - Day Five Double click on Main Intermediate Language code will appear.
    Learna Tiny Bit of C# in Seven Days - Day Five 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.

    classProgram    {       staticvoid Main(string[] args)        {           var name;       }      }   

    Learna Tiny Bit of C# in Seven Days - Day Five Figure 31: Implicit type variable without initialization
    • Var keyword cannot be null,

    classProgram    {       staticvoid Main(string[] args)       {           var name = null;       }      }   

    Learna Tiny Bit of C# in Seven Days - Day Five                      Figure 32:  Var keyword cannot
    • You cannot use object or collection initializers:

    classProgram    {       staticvoid Main(string[] args)       {           var array =            { 1, 3, 4, 5 };       }   }   

    Learna Tiny Bit of C# in Seven Days - Day Five Figure 33:  Error demonstrating we cannot use object or collection initializers

    namespace Var   {       classProgram       {           staticvoid Main(string[] args)           {               var value = 1;               var name = "Saillesh";               var array = newint[]                {                   1,                   3,                   4,                   5,                   6               };               Console.WriteLine(value);               Console.WriteLine(name);               foreach(int i in array)                {                   Console.WriteLine(i);               }               Console.ReadLine();           }          }   }   

    Output:

    Learna Tiny Bit of C# in Seven Days - Day Five 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:

    publicclassCustomer   {       privatestring _customerName;          publicstring customerName       {           get;           set;       }          privatestring _customerAddress;       publicstring customerAddress       {           get;           set;       }      }   

    When we instantiate this class we normally write code,

    staticvoid Main(string[] args)    {       Customer objCustomer = newCustomer();       objCustomer.customerName = "Saillesh Pawar";       objCustomer.customerAddress = "Mumbai";   }   Or   staticvoid Main(string[] args)    {       Customer objCustomer = newCustomer()       {           customerName = "Saillesh Pawar",               customerAddress = "Mumbai"       };   }   Or we can do the same using Var keyword      var objCustomer = newCustomer()    {       customerName = "Saillesh Pawar",           customerAddress = "Mumbai"   };   

    4.2

    Initializing Collections

    Let’s take an example of a generic list as shown below,

    List < string > objstringList = newList < string > ();   using System;   using System.Collections.Generic;   using System.Linq;   using System.Text;   using System.Threading.Tasks;      namespace Var   {       publicclassAuthor       {           string _author;           List < string > _articles = newList < string > ();           publicstring author           {               get               {                   return _author;               }               set                {                   _author = value;               }           }              publicList < string > articles            {               get               {                   return _articles;               }               set                {                   _articles = value;               }           }          }             classProgram       {           staticvoid Main(string[] args)            {               List < Author > authorList = newList < Author > ();               Author objAuthor = newAuthor();               objAuthor.author = "Saillesh Pawar";               objAuthor.articles.Add("Learn C# day 1");               objAuthor.articles.Add("Learn C# day 2");               objAuthor.articles.Add("Learn C# day 3");               objAuthor.articles.Add("Var keyword");               authorList.Add(objAuthor);                  Author objAuthor2 = newAuthor();               objAuthor2.author = "Nishant Negi";               objAuthor2.articles.Add("Essence of Life");               objAuthor2.articles.Add("Serve your Nation");               objAuthor2.articles.Add("My life");               objAuthor2.articles.Add("Enroute to Ladakh");               authorList.Add(objAuthor2);                  Console.WriteLine(objAuthor.author + " Articles Published /n" + objAuthor.articles[0] + "/n" + objAuthor.articles[1]);               Console.WriteLine(objAuthor2.author + " Articles Published /n" + objAuthor2.articles[0] + "/n" + objAuthor2.articles[1]);               Console.ReadLine();           }             }   }   

    Now same can be done with less amount of code using Var.

    using System;   using System.Collections.Generic;      namespace Var   {       publicclassAuthor        {           string _author;           List < string > _articles = newList < string > ();           publicstring author            {               get                {                   return _author;               }               set               {                   _author = value;               }           }              publicList < string > articles            {               get                {                   return _articles;               }               set               {                   _articles = value;               }           }       }       classProgram       {           staticvoid Main(string[] args)            {               var autorList = newList < Author > ()                {                   newAuthor                    {                       author = "Saillesh Pawar",                           articles =                            {                               "Learn Tiny bit of c# day1",                               "Learn tiny bit of C# day2"                           }                   },                   newAuthor                   {                       author = "Nishant Negi",                           articles =                           {                               "Enjoy the life",                               "Enroute to Ladakh"                           }                   }               };               //Diplaying 1st author and his/her articles               Console.WriteLine("Author name " + autorList[0].author + "Articles Published in 2015 /n 1." + autorList[0].articles[0] + " /n 2." + autorList[0].articles[1]);                  //Diplaying 2nd author and his/her articles               Console.WriteLine("Author name " + autorList[1].author + "Articles Published in 2015 /n 1." + autorList[0].articles[1] + " /n 2." + autorList[0].articles[1]);               Console.ReadLine();           }             }   }   

    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:

    var obj = new   {       Name = "saillesh",           Address = "Mumbai"         };   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:

    using System;   using System.Collections.Generic;   using System.Linq;   using System.Text;   using System.Threading.Tasks;   using System.Xml.Linq;      namespace Anonymous    {       publicclassMeetingMaster        {           publicint MOMId            {               get;               set;           }           publicint SegmentId           {               get;               set;           }           publicint MeetingNameId           {               get;               set;           }           publicstring Description           {               get;               set;           }          }       publicclassMeetingNameMaster        {           publicint Id           {               get;               set;           }           publicstring MeetingName           {               get;               set;           }       }             classProgram       {           staticvoid Main(string[] args)           {               var meetingList = newList < MeetingNameMaster >                    {                   newMeetingNameMaster                   {                       Id = 1,                           MeetingName = "RMS"                   },                   newMeetingNameMaster                   {                       Id = 2,                           MeetingName = "Functional"                   },                   newMeetingNameMaster                   {                       Id = 3,                           MeetingName = "Hr"                   }                  };                  var meetingMaster = newList < MeetingMaster >                   {                   newMeetingMaster                   {                       MOMId = 1,                           MeetingNameId = 1,                           Description = "RMS Funtional covered",                           SegmentId = 1                   },                   newMeetingMaster                   {                       MOMId = 2,                           MeetingNameId = 1,                           Description = "Functional Agenda Covered"                      },                   newMeetingMaster                   {                          MOMId = 3,                           MeetingNameId = 1,                           Description = "Rms functional covered responsibility taken by saillesh pawar",                           SegmentId = 1                      }               };                  var rmsMeetingCommenced = (from mtnMaster in meetingMaster join meetings in meetingList on mtnMaster.MeetingNameId equals meetings.Id selectnew {                      MOMId = mtnMaster.MOMId,                       Desciption = mtnMaster.Description,                       MeetingName = meetings.MeetingName               }).ToList();                           foreach(var i in rmsMeetingCommenced)               {                   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);                  }                  Console.ReadLine();                       }       }   }   
  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:

    using System;      namespace ConsoleApplication3    {       publicstaticclassMyClass        {              publicstaticint Square(thisint Number)           {               return (Number * Number);           }          }             classProgram       {           staticvoid Main(string[] args)            {                  Console.WriteLine("Enter the Number");               int Number = Convert.ToInt32(Console.ReadLine());               int squareResult = Number.Square();               //We can call the method as it is instance member               Console.WriteLine("The square of the number is " + squareResult);               Console.ReadLine();              }       }   }   

    Output:
    Learna Tiny Bit of C# in Seven Days - Day Five          Figure 34:  Calling Extension Method
    We can do the same without extension method:

    int squareResult = MyClass.Square(Number);   

Read more articles on C# :

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Learna Tiny Bit of C# in Seven Days – Day Five

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
分享按钮