Dynamic Keyword in C#

    Dynamic Keyword    

    In C# 4.0 dynamic keyword was introduced, the advantage of dynamic keyword is that the actual type of variable of dynamic type is decided at run time. You can initialize the variable of dynamic type with any type of value or even if you do not initialize the value then also it will not give any error.

    You can also change the value of a dynamic variable to any other type, e.g. if you assign a integer value to a dynamic variable at the time of initialization then later you can also change it to string type of value and you will not get any error.

    Let us look at an example of dynamic type of variable below.

As you can see in the above example we have declared a dynamic type variable a and we have not initialized the variable, then we assigned the integer value to it and then later assigned a string type of value, when we build the code we did not get any error and the build has been succeeded.

    Dynamic keyword is very useful when working with LINQ queries as we can store the output of the LINQ query in the dynamic keyword.

    Difference Between dynamic Keyword and var Keyword .

Dynamic

 

Var

dynamic is a dynamically typed variable.

             

var is a statically typed variable.

dynamic typed variable is not mandatory to initialize at the time of declaration. 

 

You need to assign a value to var type of variable at the time of declaration else you will get a compile time error.

 

You can also change the value of dynamic variable to any other type other than the type of value which was assigned before.

 

You cannot assign the value of any other type to var variable other than the type of value which was assigned when it was initialized else you will get a compile time error.

 

You can use dynamic type as a method return type and as a type of parameter passed to a method.

 

You cannot use var type of variable as a method return type or parameter passed to a method.

dynamic keyword was introduced in C# 4.0.

           

var keyword was introduced in C# 3.0.

    So we have looked in this article how we can use dynamic keyword in C#, and also the difference between dynamic and var keyword, I hope you find this article useful.

    For more information on C#, .NET please read my other articles. 

    If you have any queries related to C#, .NET or to provide any feedback, please write a mail on prson94@gmail.com and I will try to get back to you as soon as possible.

    If you like the article then please write it in the comments box as it will motivate me to write more articles.

    Thank You...….

Sealed Class in C#

Sealed Class


    Sealed classed can not be inherited, if you try to inherit from a sealed class then you will get a compile time error. Sealed classes are declared using sealed keyword as shown below.

public sealed class sealedClassDemo
    {
       
    }

    As shown in the below example we are trying to inherit from a sealed class and on the same time we can see a error message saying that we can not inherit from a sealed class.

    


    The most common use of sealed class is to stop the inheritance but you can still extend the sealed class using extension methods. So as shown in the below example we can extend the sealed class by having a extension method, to know more about extension methods please read my blog on extension methods in C#.

    


     So today we have discussed regarding sealed class in C# and there importance, how sealed keyword can be used.

    Thank You for taking your time and reading my post on sealed class, please read my other posts related to C#, jQuery and .NET.

    If you have any other questions related to .NET or C# then please write them in the comments section or write a mail on prson94@gmail.com and I will try to get back to you as soon as possible.

Class and Object in C#

 Class and Object

    Class in C# contains different data members and functions/methods and it binds them together. We can access the data members and functions of a class using objects of a class. Class is nothing but a blueprint of a object. You will better understand class by looking at following example.

    public class Test
    {

            //Data Members of a class

            int a, b;

            public void foo()
            {

                    // Method implementation
             
            }
    }    
  
As shown in the above example, we have created a class called Test and to define a class we have used class keyword. The class contains two data members as a and b and one function foo. We can access those data members and function by creating object of the class. We have used public access modifier for the class so that we can access the class outside of the class. By default access modifier for a class is internal. We can create an object of the class using new keyword as shown below.

        Test tst = new Test();

We can initialise the data members of the class using constructors in C#, to know more about please read my blog on constructors here.

So we have discussed about class and objects in C# today, please read my other blogs on .NET for more information.

For any issues related to C#, ASP.NET, jQuery or to provide any feedback please write to me on prson94@gmail.com, I will try my best to reply you as soon as possible.

Async and Await in C# - Asynchronous Programming

Async and Await  

   Async and await are the two most important keywords in C# while doing asynchronous programming. Async keyword is used to in the signature of a method to denote that this method will be executed asynchronously, if you are making a method async then you need to use await keyword in the method. Await keyword is used to denote that the method execution will not processed unless all the task which needs to be executed are complete.

    You will get an better idea of Async and Await keyword with below example. As shown in the below example we have run the same code synchronously and asynchronously, and we have captured the time required for both the codes to be executed. As you can see we are iterating through a same list of string 4 times to find a match for a particular string, and then we have added a 1000 millisecond sleep time between execution of each iteration.


    
    If you see the time taken by running the code asynchronously and synchronously then you will find out that time taken for asynchronous execution of code is much less than the synchronous execution of code. Please find the output of console window below.

    

   

    So in the asynchronous execution of code while executing the executeList method code, we have created different task for iteration and then that other tasks do not wait for the first task to get complete, all the tasks starts executing parallelly and the time taken to execute the whole code is the maximum taken by an single iteration. In synchronous code execution, it waits for the first iteration of the code to be complete and then the second iteration of the code start executing so it has to wait for 1000 millisecond which is added by us before start executing the other code. You can think the wait of 1000 millisecond added by us any other action which needs to be executed in the practical example of the code.

   So to conclude asynchronous coding gives you an edge while executing the code but it needs to be used carefully and over use of asynchronous code and no proper use of asynchronous coding can led to system degradation.

    Thank you for reading this blog and please read my other blogs on different topics related to C#. If you any other query related to C#, .NET or jQuery or to provide any feedback please write to me on prson94@gmail.com and I will try to get back to you as soon as possible.

Thank You...…..

Email Id - prson94@gmail.com

Extension Methods in C#

Extension Methods


    Extension method in C# enable us to extend the functionality of a type without deriving from it, in simple terms we can add a method to an existing type. Extension method is a static method in a static class. Extension method will be very clear when you will see below example.

     So as you can see in the below example we have created a static class ExtensionDemo and in that we have a static method ToUpperLower which modifies the string passed to method and then returns the method. In the ToUpperLower method we are changing alternate character in the string to upper case. Now as you can see, we can call the ToUpperLower method on a string type of variable as the first parameter accepted by extension method which needs to be accepted using this keyword is of string type.


    
   

    Now in the console window you will see the output as "HeLlO WoRlD". 




    All the extension methods are denoted by a downward arrow symbol as show below.



Few important points to related to extension method are as below:

  • Extension method feature is available from C# 3.0.
  • Extension method must be a static method in a static class.
  • First parameter of an extension method must start with this keyword of a given type in .NET.

So today we have looked in to the extension methods, and how we can use them in C#.

Thank You...…



For any issues related to C#, .NET, or jQuery please or to provide any feedback please write to me on prson94@gmail.com and I will try my best to get back to you as soon as possible.


Constructors in C#

 Constructors


    Constructors are used to initialize the data members of when an instance of a class is created. Name of the constructor is always same like class name. Find the example of an constructor below.

        class Test 
    {

        public Test()  -------> Constructor
        {
    
        }
    
    }

    As shown in the above example, we have class named as Test and then we have constructor with same name, constructor are like a method in a class but they have a same name as that of class with no return type. 

    Few important points to remember regarding constructors in C#.

  • Constructor have same name as that of class.
  • Constructor do not have any return type, not even void.
  • There can be more than one constructor for a class.
  • Static constructor can not have any parameters and also they do not have any access modifier.

    There are different types of constructors as mentioned below.

  • Default Constructor     
  • Parameterized Constructor
  • Copy Constructor 
  • Private Constructor
  • Static Constructor
    Let us now look different types of constructors one by one.

Default Constructor:

    Even if a class do not have any constructor then also a default constructor is automatically created by the compiler. Automatically created default constructor do not accept any parameters. If we create a constructor in a class then always that constructor is called whenever we create an instance of an object.
Let us look at an example of default constructor.
    
    public class Test 
{          
           public string str;

           public Test() 
      {
           str = "Hello From Constructor";
      }
    
 }


    public class Main
{
        public void Demo()
   {
            Test tst = new Test();
            Console.Writeline(tst.str)
   } 
}

    As shown in the above example we have created a class Test and its constructor and then initialized one of the data member of the class inside the constructor. Once an instance of the class is created then the constructor is called automatically and then the in the output we will see as "Hello From Constructor".


Parameterized Constructor:

    Using parameterized constructor we can initialize the data members of the class for that object, while creating an object for a class we can pass the values through which we can initialise the data members for that class. Let us look at this with an example below.

    public class Test 
{            
       public int a;
       public int b

       public Test(int _a, int _b) 
      {
           a = _a;
           b = _b;
      }
    
 }


public class Main
{

    public void Demo()
   {
            Test tst = new Test(10,20);
            Console.Writeline(tst.a.ToString());
            Console.Writeline(tst.b.ToString());
   }
 

}

    As shown in the above example we have created a class Test and its constructor and then initialized the data member of the class inside the constructor using the parameters passed to the constructor. Once an instance of the class is created then the constructor is called by passing those two parameters and then in the output we will see as 10 & 20.

Copy Constructor:
    
    Copy constructor is used to create an exact copy of an object by passing that object as a parameter to the constructor. Please find the example of copy constructor below.


    public class Student
{
        
        public string _firstName;

        public string _lastName;

        public Student(Student std)
        {
                _firstName = std.firstName;
                _lastName = std.lastName;
        }

        public Student(string firstName, string lastName)
        {
                _firstName = firstName;
                _lastName = lastName;
        }
}


    public class Main
{
        public void Demo()
    {
            Student st = new Student("Prasad","Sonawane");
            Student st1 = new Student(st);
            Console.Writeline(st1.firstName);
            Console.Writeline(st1.lastName);
            
    }

}

As shown in the above example we have created a class Student and there are two types of constructor for the class, one is parameterised constructor and the other one is copy constructor so as we can see we are passing the whole object as parameter to the constructor and in the output we can see as "Prasad Sonawane".


Private Constructor:

    Private constructor can not be called from outside the class, one of the practical example for which private constructor can be used is to initialise the static members of the class. 
 

Static Constructor:

    Static constructor can be used to initialise the static members of the class, and in the static constructor we can not pass the parameters. Static constructor can not be called explicitly but it is executed during the creation of the first instance of the class or if any of the static members of the class is referenced. Static constructor is declared using static keyword. Below is the example of the static constructor.

    public class Student()
{
        static Student()
    {
    
    }
}

So today we have looked what is constructor in C#, how it can be used and its importance, also we have looked in different types of constructors.

For any issues related to C#, ASP.NET, jQuery or to provide any feedback please write to me on prson94@gmail.com, I will try my best to reply you as soon as possible. 

Thank You...….

Email Id - prson94@gmail.com.

Interfaces in C#

 Interfaces


    Interfaces in C# are like pure abstract class. Any method in an interface can not have implementation and we can only provide the declaration of those methods. All the methods in an interface are by default marked as abstract and public and we need not to mention that. Using interface we can also achieve multiple inheritance in C#. We also can not create an object of interface and to use the data-members and methods, and to use the data members and methods of the interface we need to implement that interface using a class.

    Interfaces in C# can be declared as below. 

     public interface Itest 
    {

    }

    It is not compulsory but the name of an interface should start with 'I' as per the naming convention as shown above. Any class that implements an interface needs to implement all the methods present in the interface.
    
    Let us look at a simple example of an interface below.

    public interface Itest
{
            string A { get; set;}
     
            int foo();
                          
}

    public class Test1 : Itest
{
  
       public int foo()
   {
        // Provide the implementation here
   }

       public string A { get ; set ; }

}


    As shown in the above example we have created one interface as Itest and that interface has been implemented by class Test1.
    A class can inherit from more than one interface and hence we can achieve multiple inheritance in C# using interfaces. If both the interfaces contain method with a same name, number of parameters in return type then we need to implement the methods in the class explicitly. Let us look at the explicit implementation of the interface below.


       public interface Itest1
{
          
                void foo();
                          
}

       public interface Itest2
{
          
     
            void foo();
                          
}


    public class Test1 : Itest1, Itest2
{
  
       public void Itest1. foo()
   {
        Console.Writeline("in method Itest1 foo");
   }
    
       public void Itest2. foo()
   {
        Console.Writeline("in method Itest2 foo");
   }

}

    public class Main

{
        Itest1 I1;    // Variable of Interface Itest1

        Itest2 I2;   // Variable of Interface Itest2

        I1 = new Test1();  // Object which is referencing to Class Test1

        I2 = new Test2(); //  Object which is referencing to Class Test2

}

    As shown above if we are inheriting from more than one interfaces and if all the interfaces contain a method with the same name then we need to explicitly mention which method we are implementing in the class.

So today we have seen how we can use interfaces in C#. and their importance. 

Thank You...….


For any issues related to C#, .NET, jQuery or to give any feedback please write to me on below mail id.


Email id : prson94@gmail.com