Monday, 28 October 2013

Difference Between Var and Dynamic Keyword in C#

Many people have expressed confusion around the difference between var and dynamic in C#.  For both of them, the type is inferred rather than explicitly declared. 
dynamic test = 1;
var test2 = 2;
If I hover my mouse over the “var” in the code above, IntelliSense will show me that the compiler has correctly inferred that it is an Int32.  If I hover over “dynamic”, it will continue to be typed as “dynamic” since dynamic types aren’t resolved until runtime. 
However, var is statically typed, and dynamic is not. 
// Can a dynamic change type?  
dynamic test = 1;
test = "i'm a string now";  // compiles and runs just fine
var test2 = 2;
test2 = "i'm a string now"; // will give compile error
This is one of the key differences between dynamic and var.  A var is an implicitly typed variable that is inferred by the compiler, but it is just as strongly typed as if you had explicitly typed it yourself using “int test2 = 2;”.  A dynamic variable bypasses all compile-time type checking and resolves everything at runtime.  
I’ll comment out the last line in the code above to get the code to compile, and add some code to verify the types of the variables. 
// Can a dynamic change type?  
dynamic test = 1;
Console.WriteLine("Dynamic as " + test.GetType() + ": " + test);
test = "i'm a string now";  // compiles and run just fine
Console.WriteLine("Dynamic as " + test.GetType() + ": " + test);
var test2 = 2;
//test2 = "i'm a string now"; // will give compile error
Console.WriteLine("Var as " + test2.GetType() + ": " + test2);
This produces the following output:
Dynamic as System.Int32: 1
Dynamic as System.String: i'm a string now
Var as System.Int32: 2




Object Dynamic Var
Can able to store any kind of value, because object is the base class of all type in .net framework. Can able to store any type of the variable, similar to old VB language variable. Can able to store any type of value but it require to initialize at the time of declaration.

Compiler has little information about the type

Compiler doesn't have any information about the this type of variable.

It's compiler safe i.e compiler has all information about the stored value, so that it doesn't cause any issue at run-time.

Object type can be passed as function argument and function also can return object type Dynamic type can be passed as function argument and function also can return object type Var type can not be passed as function argument and function can not return object type. This type of variable can work in the scope where it defined.

Require to cast object variable to original type before using it. So this assigning to object type and converting to original type called as Boxing and Un-Boxing for value type and for the reference type its casting of types. It's actually increasing the overhead when we do this both operation.
Allows to perform operation of given type once it get cast any user defined or primitive data type.
Casting is not require but you need to know the property and methods related to stored type No need to cast because compiler has all information to perform operation.
Cause the problem at run time if the stored value is not get converted to underlying data type.

Cause problem if the wrong method or property accessed because all the information about stored value is get resolve only at run time

Doesn't cause problem because compiler has all info about stored value.
Useful when doesn't have more information about the data type. Useful when coding using reflection or dynamic language support or with the COM objects, because we require to write less amount of code. Useful when getting result out of the linq queries. In 3.5 framework it introduce to support linq feature.

Difference Between Encapsulation and Abstraction

What is encapsulation?

Encapsulation is the process of hiding irrelevant data from the user. To understand encapsulation, consider an example of mobile phone. Whenever you buy a mobile, you don’t see how circuit board works. You are also not interested to know how digital signal converts into analog signal and vice versa. These are the irrelevant information for the mobile user, that’s why it is encapsulated inside a cabinet.
In C# programming, we will do same thing. We will create a cabinet and keep all the irrelevant information in it that will be unavailable for the user.

Encapsulation is wrapping, just hiding properties and methods. Encapsulation is used for hide the code and data in a single unit to protect the data from the outside the world. Class is the best example of encapsulation.

What is abstraction?

Abstraction is just opposite of Encapsulation. Abstraction is mechanism to show only relevant data to the user. Consider the same mobile example again. Whenever you buy a mobile phone, you see their different types of functionalities as camera, mp3 player, calling function, recording function, multimedia etc. It is abstraction, because you are seeing only relevant information instead of their internal engineering.

We use abstraction in programming languages to make abstract class. Abstract class represents abstract view of methods and properties of class.

Implementation Difference Between Encapsulation and Abstraction

1.  Abstraction is implemented using interface and abstract class while Encapsulation is implemented using private and protected access modifier.

2. OOPS makes use of encapsulation to enforce the integrity of a type (i.e. to make sure data is used in an appropriate manner) by preventing programmers from accessing data in a non-intended manner. Through encapsulation, only a predetermined group of functions can access the data. The collective term for datatypes and operations (methods) bundled together with access restrictions (public/private, etc.) is a class.

3. Example of Encapsulation

Class Encapsulation
{
    private int marks;

    public int Marks 
   {
      get { return marks; }
      set { marks = value;}
    }
}

4. Example of Abstraction

abstract class Abstraction
{
    public abstract void doAbstraction();
}

public class AbstractionImpl: Abstraction
{
    public void doAbstraction()
   {
       //Implement it
   }
}