Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

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 a 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.

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# - Inheritance



There are four main concepts present in OOPs

  • Inheritance 
  • Polymorphism
  • Encapsulation  
  • Abstraction

Today, we will discuss about the first OOPs concepts which is inheritance.

Inheritance

With inheritance we can use the variables or methods of one class into another class. Inheritance is very widely used concept of OOPs in C#. There are mainly two types of inheritance

  • Multiple Inheritance
  • Multi-Level Inheritance

Multiple Inheritance:

In multiple inheritance we can inherit from more than one class e.g. suppose there are three class A, B & C, so A can inherit from B & C. 

e.g.

public class A
{

}

public class B
{

}

public class C : B, A
{

}

Multiple class inheritance is not supported in C#.


Multilevel Inheritance:

In Multilevel inheritance B can inherit from A and C can inherit from B.

e.g.

public class A
{

}

public class B : A
{

}

public class C : B
{

}

Multilevel class inheritance is supported in C#.

With inheritance we can reuse the code of parent class in the base class.

e.g. if we have a parent class and child class then child class can inherit from parent class and use its data variables and methods.

    class Program
    {
            static void Main(string[] args)
            {        
                    child c = new child();
                    c.a = 20;
                    c.b = 10;
                    int result  = c.Addition();

                    Console.WriteLine(result.ToString());

                    result = c.subtraction();

                    Console.WriteLine(result.ToString());

                    Console.ReadLine();
            }
    }

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

        public int Addition()
        {
            return a + b;
        }

    }

    public class Child : Parent
    {

        public int subtraction()
        {
            return a - b;
        }

    }

So in the above example child is inheriting from Parent class and even though Child class do not have variable a & b still we can use them in the subtraction method of Child class as they are present in the Parent class.

We have created a object of Child class and we can call the method Addition with Child class object as we have inherited from Parent class in Child class. So by using inheritance we can achieve code re-usability.

The output of the above code will be 30 & 10.

So today, we have seen how we can achieve inheritance in C#, The other OOPs concepts we will discuss in my next post.

Thank You...….


For any issues regarding C# OOPs concepts please write to me on below mail Id and I will surely get back to you.