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
    


Abstract Class in C#

 Abstract Class 


    We can not create an object of an abstract class in C#, so we need to inherit the abstract class using another normal class and then we can use the methods and data members present in the abstract class.
In the abstract classes we should not provide the whole implementation of logic but we should only have the outline of the class and then we can inherit the class to provide the full implementation of the class.
    Abstract classes are declared using abstract keyword as shown below.

    public abstract class Vehicle
   {

    }


    If we need to take a real time example of the abstract class then we can imagine an abstract class as a Vehicle which can provide all the data members like steering, tires, gear etc and then we have a abstract methods in the class which can only have declaration and not the implementation like driving. We can then create a normal classes like Swift, Wagonr, Maruti which are different types of vehicles and those classed can inherit from the main class Vehicle and using the data members of the Vehicle class provide the full implementation of  driving method present in the Vehicle class. As every child class has a different implementation for the driving method hence we can override the abstract method in the child class and gives its own implementation. 

    Please find the  example below:

     public abstract class Vehicle
 
{
            public string steering { get; set;}
            
            public string tyres {get; set;}

            public string gear {get; set;}


            public abstract void driving();

  }

    public class Swift : Vehicle
    
{    
     
        public override void driving()
     {
            // Provide the implementation here
     }    


}

Few important points to remember related to abstract class in C# as below.

  • We need to declare an abstract class in C# using abstract keyword.
  • Abstract class can have abstract as well as non abstract methods.
  • Abstract methods needs to be declared with abstract keyword and they can not have implementation.
  • When we inherit any abstract class then we must implement the methods in the child class which are marked as abstract in abstract class.

So today, we saw how we can use abstract classes in C#, their importance. 

Thank You …..

For any issues related to C#, .NET or for any feedback then please write to me on below mail Id and I will surely get back to you.

Email Id : prson94@gmail.com



OOPs Concept in C# - Polymorphism

 Polymorphism


Polymorphism is one of the important concepts in OOPS, if you break the word into two parts then you will understand its meaning. Poly means many and morph means forms.

So we will be discussing how polymorphism is used in C#. There are basically two main types of polymorphism in C# as below.


  • Method Overloading.
  • Method Overriding.


So first we will understand method Overloading.

Method Overloading:

  In method overloading we have same method name for more than one method in a class but either the number of parameters for the method or data type of method are different. It is important to note that we can not have two methods with same method name, same number of parameters and there datatypes but different return type.

Let us understand the concept with an example.

So suppose if I have a class name as Test and in there I have two methods with the same name as add()
but if you look at those two methods then you will understand that both of them are accepting difference number of parameters.

public class Test 
{
        
      public int add(int a , int b)
     {
            return a + b;
     }    

     public int add(int a, int b, int c)
    {
            return a + b + c;
    }    


}

So when you build your code you will see that you have not encountered any errors even though both the methods are having same name, but if make the number of parameters and there data types same in both the method then you will get a compile time error.


Let us now discuss about method overriding.

Method Overriding:

    Method overriding means we can override implementation of method which is present in the parent class in child class. To override a method first we need to inherit from the parent class and the parent class needs to be a declared with virtual keyword.

    Let us understand this with an example so that you will get an clear idea. So we have a parent class as Parent and child class as Child and we have a method in the parent class named as foo() which is declared with keyword as virtual.

    public class Parent
    {
            public int a;
            public int b; 

            public virtual int foo(int a, int b)
            {    
                  //Implementation of parent foo method
            }
            
    }

    public class Child : Parent
    {
            public override int foo(int a, int a)
            {
                // implementation of child foo method.
            }                
    }


So as shown in the above example if you see we have overridden the implementation of foo() method in the child class and in the child class we can use the parent class data members a & b so it gives us code reusability also and child class can have its own functionality.

So if I need to give an example of method overriding in real life world then think of it as Car and different types of cars, so every car has a ability to move/drive but then each type of car like Swift, WagonR, i10 etc. will have its own type of implementation to get driven but every car have same data members like steering, wheels, gear etc...


So today, we have seen how we can use polymorphism in C#, we will discuss other OOPs concepts and many more things in my next post.


Thank You...…..

For any issue regarding C# or .NET please write to me on below mail id and I will try my best to reply.

Email Id : prson94@gmail.com.