Friday, August 5, 2016

Generic, Dynamic, Object C#

Generic
  • allow you to delay the data type until actually used in program, 
  • allow the class or method work with any data type.
  • define types at compile time.They don't change
static void Main(string[] args)
{
    Compare<string> i = new Compare<string>();
    Console.WriteLine(i.Check("a", "a"));
    Console.ReadLine();
}

class Compare<T>
{
    public bool Check(T a, T b)
    {
        return a.Equals(b);
    }
}

Dynamic 
  • new for .NET 4.0.
  • reference types
  • specify the type at run time 
  • allows you do dynamically add and change properties and methods without the compiler checking them (so if what you wrote is wrong you will only find out at runtime).
Dynamic vs Generic
defined at runtime. You don't have compile-time type safety there. The dynamic class is similar as if you have object references and call methods by its string names using reflection.


  • Type safety:  Dynamic variables will not alert you with compile time warnings/errors in case you make a mistake, it will show runtime error when running the system 
  • Performance : Generics improves the performance for code using Value types by a significant order of magnitude. It prevents the whole boxing-unboxing cycle that cost us pre-Generics. Dynamic doesn't do anything for this too.
Object
  • valid for all .NET versions.
  • reference types
  • It is the base type that all other types inherit from, so any type can be cast to object.
  • can't dynamically add and change anything on a variable declared as object.
  • The declaration is a statically typed and checked by the compiler.
Dynamic vs Object
Dynamic allow mathematically, Object No

No comments:

Post a Comment