Interviews5 answers
What is difference between object, var and Dynamic?
5 Answers
Object-Able to store any kind of value, because object is the base class of all types in .NET Framework.
public void CheckObject()
{
object test = 10;
test = test 10; // Compile time error
test = "hello"; // No error
}
Dynamic-Able to store any type of the variable, similar to old VB language variable.
public void CheckDynamic()
{
dynamic test = 10;
test = test 10; // No error
test = "hello"; // No error, neither compile time nor run time
}
Var-Able to store any type of value but it is required to initialize at the time of declaration.
public void CheckVar()
{
var test = 10; // after this line test has become of integer type
test = test 10; // No error
test = "hello"; // Compile time error as test is an integer type
}
Debasis MohapatraPosted Jan 17, 2019, 12:54 AM EST
object can contain any type of value and u can use object as parameter.
var can contain any type of value but must assign value at declaration time.
and dynamic can store any kind of value like dynamic a = 1; a= 'abc'. no type is matter.
Mehul PrajapatiPosted Jan 27, 2018, 4:03 AM EST
Everything in .net is derived from System.Object type.
Difference between Object and dynamic.
1.You cannot implicitly cast a variable of type Object into any other type. Compiler will not let you do that. On the other hand you can implicitly cast any type to dynamic. Compiler will not complain because casting will be performed during run time and exception, if required will raised during run time.
2.Because dynamic is same as object, You cannot write overloaded methods which differ in Object and dynamic in arguments.
Difference between dynamic and var.
1.Declaring a local variable as dynamic or var has only syntactical difference.
2. You cannot declare a variable of type var without initializing it, But you can do that for a dynamic variable
3. You cannot use a var variable to pass as method argument or return from a method.
4. You cannot a cast an expression to var but you can do it for a dynamic variable.
Tushar DikshitPosted Nov 6, 2017, 12:46 AM EST
Object is instance of class
Var is variable
Dynamic means run time changes
Neha KumariPosted Nov 5, 2017, 8:38 AM EST
Object is a base type in .NET. All others types are inherit from it.
Var is not a type, but the instruction for the compiler to conclude a variable type from the program context.
Dynamic – is a special type for which the compiler don't do type checking at compile time.
Khushbu DesaiPosted Oct 7, 2017, 1:35 AM EDT



