C# has prosperous data types for storing any data/information. We have three sorts Object, Var, and Dynamic for storing any data in C#. So how about we observe how these three separate with each other with cases.
Object:
It was first introduced in C# version 1.0. An Object is a base class of .Net as we all know, its purpose is the same, it can store all kinds of data. It is a compile-time variable. We can also pass objects as method arguments because methods can return Object type. At compile time compiler doesn't have much information for the use type, so it is very productive when we don't know the type of data. But when we have to use data inside an object we need to cast it to the required data type. The object is the most abstraction for all types in C# and its reference type. An object can box any type of data. When using an object to store data that is called boxing and for using that data need to unbox it.
Object emp_id = 10; // int
Object order_porduct = new Order(); //order object
Object customer_name = "John"; //string
//unbox
string customer = customer_name.ToString();
//perform string operation now
customer.Trim();
Var:
It comes in C # 3.0 versions. Var is a compile-time variable. It is also used to store any type of data, but the additional work is that declaration time we have to initialize the var type is mandatory. So that's why var type can only work within the specified scope not out of this because its method does not return object type and also cannot be passed as a method argument, but it's a type-safe and compiler know all data, which is stored in var type. That's why while using we are not required to cast var type we can directly use it.
var qty = 10; // int
var brder_ID = 10d; // double
var brand = "samsung"; // string
Dynamic:
In C# 4.0 we got dynamic a run-time variable that can store all kinds of data. The dynamic keyword has some same characteristics as Object that it doesn't have any information about data and not type-safe, but an advantage we have that it can be passed as a method argument in return it gives dynamic type. It does not require cast when using its data, but we should have knowledge that which properties and methods are linked with stored data type because if we use any other property or method, then it will throw an error. We can use it when doing code with reflection, dynamics, or playing COM objects because in a very short time we can code big tasks with fewer lines.
dynamic employee = new Class();
employee.Age = 30;
employee.Name = "John Doe";
employee.Course = new Course();
employee.Name; // read a string
employee.Age; // read an int
employee.Course.Name; // read a property
very nice post..
ReplyDelete