Knowing
var, dynamic and object
object
Everything in
.net framework is inherited from object class. This is a base type. Every datatype
can be boxed in the object type
Example
object a = 10; // int
object b = new Customer(); // customer
object
object c = new Product(); // product
object
object d = "Jon"; // string
object e = new { Name = "Felipe", Age = 20 }; // anonymous
type
var
var is a keyword
in c#. It allows you to define a variable which can contain any type. Once it
is assigned a type the variable can contain only that type
Example
var a = 10; // int
var b = 10d; // double
var c = "text"; // string
var p = new Product(); // Product type
Here if we
try to use the ‘a’ again and assign string data to it, it will now allow.
dynamic
As the name
suggest dynamic is a special type which does not compile during normal
compilation period. It is used when the output or the input type is unknown,
also you can reuse the same variable and assign any type to it during the same
method run
Example
dynamic cust = new CustomerDetails();
cust.Age = 18;
cust.Name = "Ishoo";
cust.Name; // string
cust.Age; // int
To learn more
on dynamic and var download the project from gihub and look for ‘Accessing and setting private or internal of different
project using reflection’
region in Main of program.cs