Difference between Object, Dynamic and Var
Everything is Object
because it is a base type for every type in .net environment. Every type inherit from Object
in a moment, a simple int
variable can be boxed to an object
and unboxed as well. For 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
It is the most abstraction for any type and it is a reference type. If you want to get the real type, you need to unbox
it (using a conversaion strategy such as methods, casts, etc):
object a = "Some Text";
string text = a.ToString();
// call a string method
text = text.ToUpper();
object i = 10; // declared as object but instance of int
int intValue = (int) i; //declare as an int ... typed
Dynamic
is an implementation of a dynamic aspect in C#, it is not strongly typed. For example:
dynamic a = new Class();
a.Age = 18;
a.Name = "Jon";
a.Product = new Product();
string name a.Name; // read a string
int age = a.Age; // read an int
string productName = a.Product.Name; // read a property
a.Product.MoveStock(-1); // call a method from Product property.
var
is just a keyword of the C# language that allows you define any object of a type since you initialize it with a value and it will determinate the type from this value, for example:
var a = 10; // int
var b = 10d; // double
var c = "text"; // string
var d = 10m; // decimal
var p = new Product(); // Product type
The compiler will check the type of the value you have defined and set it on the object.
var vs Object in C#
var
is just shorthand for "let the compiler pick the right variable type for me" (compile-time type-inference is the more exact term).
object
, on the other hand, is a specific type; all other reference types derive from object
, so you can assign anything to a variable of type object
.
Difference between variable and object
Creating a variable has 2 parts, Declaration and Assignment.
In the Declaration part, you state that the variable exists and you state its type:
DataRow dr; // Create's a variable of type DataRow with a value of null.
The Assignment takes a value and point the variable to it:
dr = new DataRow(); // Creates a new DataRow and points dr variable to it.
You can do them both in the same line like that:
DataRow dr = new DataRow();
The result is the same as if you would separate those into the 2 lines above and the type of the variable is in both cases DataRow
.
The object
inside the variable however can be of an inherited type:
class MyDataRow : DataRow
{
}
DataRow dr = new MyDataRow(); //Creates a new object of type MyDataRow and points dr to it.
Managed objects
must be held by a variable otherwise they are Garbage Collected.
Difference between var and object in C#
Beginning in Visual C# 3.0, variables that are declared at method scope can have an implicit type var
. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type. The following two declarations of i
are functionally equivalent:
var i = 10; //implicitly typed
int i = 10; //explicitly typed
var isn't object
You should definitely read this : C# 3.0 - Var Isn't Object
Difference between Dynamic, Var and Object
Here is some differences. Hope this will help to you.
Difference between Var type and object type in C#
Both are compiled to the same MSIL code. The only difference is a possible convenience for you while writing source code - if you decide to change the type of p
later on, you only have to replace Person
once in the constructor call and you can leave the variable declaration intact when using var
.
That said, var
goes along with a slight decrease in legibility, as you cannot see the type of p
instantly any more at the beginning of your line. Therefore, restrict your use of var
to occasions where it really saves some typing, such as for complicated nested generic types.
Note that, if you do not initialize your variable right away (in the same statement where the variable is declared), you cannot use var
as the compiler cannot infer the type of the variable.
Difference between var and Class class in object creation
When declaring a variable with the var
keyword, the compiler infers the type of the variable from the right-hand side of the assignment. In particular, it uses the type the expression on the right-hand side of the assignment operator (=
) evaluates to.
Therefore, for your declaration
var c = new C();
, the variable c
will be declared as type C
.
If you want c
to have any other type, there are basically two options:
- Either indicate the type of
c
explicitly:B c = new C();
- Alternatively, you can change your right-hand side expression to be recognized as the type of choice:
var c = (B)(new C());
As for your more detailed questions:
B c = new C()
creates an instance of typeC
. That is whatnew C()
does. The fact that variablec
is typed toB
only means that the compiler will assume thatc
has any properties and methods of typeB
, but not necessarily of typeC
. Likewise, you are allowed to assign not only instances of typeC
, but also instances of typeB
toc
at a later time.- Indeed, you can use this style when you are not sure whether
c
will at some point reference an instance of typeB
, rather than exclusively instances of typeC
.
What is the difference between var a = new className() {id = , Name = } and var a = new className {id=,Name=}}
Calling new className
opposed to new className()
will make no difference. They both call the default constructor. The spacing difference is irrelevant too.
Both code segments are rewritten by the compiler to something equivalent to:
className a = new className();
a.id = "foo";
a.Name = "sass";
Using listtype or var keyword difference
They are the same. var
is implicitly typed.
If you hover over the keyword var
in Visual Studio, it will show you the type of your object - in this case List<string>
. The use of var
is only to clean up code - you already know you're creating an object of type List<string>
, so some people think it is redundant to type:
List<string> list = new List<string>();
There is no performance difference, as the compiler already knows what type the object is. Using var personal preference mostly - you can use it if you want to and there is no performance hit.
Eric Lippert has a great blog post about var
here.
I think you're confusing var
and dynamic
, which are two totally different things. The dynamic
type is a type that allows you to assign values of different types to it at runtime.
What's the difference between dynamic (C# 4) and var?
var
is static typed - the compiler and runtime know the type - they just save you some typing... the following are 100% identical:
var s = "abc";
Console.WriteLine(s.Length);
and
string s = "abc";
Console.WriteLine(s.Length);
All that happened was that the compiler figured out that s
must be a string (from the initializer). In both cases, it knows (in the IL) that s.Length
means the (instance) string.Length
property.
dynamic
is a very different beast; it is most similar to object
, but with dynamic dispatch:
dynamic s = "abc";
Console.WriteLine(s.Length);
Here, s
is typed as dynamic. It doesn't know about string.Length
, because it doesn't know anything about s
at compile time. For example, the following would compile (but not run) too:
dynamic s = "abc";
Console.WriteLine(s.FlibbleBananaSnowball);
At runtime (only), it would check for the FlibbleBananaSnowball
property - fail to find it, and explode in a shower of sparks.
With dynamic
, properties / methods / operators / etc are resolved at runtime, based on the actual object. Very handy for talking to COM (which can have runtime-only properties), the DLR, or other dynamic systems, like javascript
.
Related Topics
JSON.Net Serialize Specific Private Field
Should I Store My Images in the Database or Folders
How to Create a Datatable in C# and How to Add Rows
Convert Bitmaps to One Multipage Tiff Image in .Net 2.0
Check If Value Exists in Datatable
How to Get a Variable's Name as It Was Physically Typed in Its Declaration
Get a Generic Method Without Using Getmethods
Incremental JSON Parsing in C#
How to List the Contents of a .Zip Folder in C#
Get SQL Query from Linq to SQL
Print Webbrowser Without Previewing I.E. Single Click Print
Does Using Tasks (Tpl) Library Make an Application Multithreaded
Convert String to Hex-String in C#
How to Initialize a List<T> to a Given Size (As Opposed to Capacity)