What is different between var, object and dynamic in C#.

var :

  1. it should be initialized
  2. We can not pass var in method as argument.
  3. Once the type is initialized it can not be changed. It become a strongly type.
  4. Var type is known at compile time. e.g var x = “strng1”; int len= x.Length, here compiler know that x is string type.

Object:

  1. It is not needed to initialize
  2. We can change and pass any type data in object.
  3. Type is resolved at run-time.

Dynamic:

  1. It is not needed to initialize.
  2. We can pass dynamic as argument in method.
  3. Has overhead on compiler for casting.
  4. Dynamic type is known at run time. e.g var x = “strng1”; int len= x.Length, here compiler uses reflection to know the type of x at run time and then check for length method in string.Dynamic internally uses reflection.

What is Early binding and late binding

Early binding also known as compile time polymorphism or method overloading.
In OverLoading – We have same class, different parameters and same method name.

Late binding also known as dynamic polymorphism or method overriding and is achieved through parent and child classes by virtual keyword.
In Overriding – We have same method name,same parameters but different classes.

Yield keyword in c#

The yield keyword effectively creates a lazy enumeration over collection items that can be much more efficient. 

Traditional way to return Ienumerator

IEnumerable<int> getnumber()
{
var i = 0; var list = new List<int>();
while (i<5)
list.Add(++i); return list;
}
foreach(var number in getnumber()) Console.WriteLine(number);

Loop with Yield

IEnumerable<int> getnumber()
{
var i = 0;
while (i<5) yield return ++i;
}
foreach(var number in getnumber()) Console.WriteLine(number);