Is the var
type an equivalent to Variant
in VB? When object
can accept any datatype, what is the difference between those two?
Nope - var just means you're letting the compiler infer the type from the expression used to assign a value to the variable. So if you have an expression like: var x = new Widget(); x will be of type Widget , not object .
Object is useful when we don't have more information about the data type. Dynamic is useful when we need to code using reflection or dynamic languages or with the COM objects and when getting result out of the LinQ queries.
dynamic variables can be used to create properties and return values from a function. var variables cannot be used for property or return values from a function. They can only be used as local variable in a function.
Var is used to declare Implicitly typed variable where the compiler identifies the type automatically. var can hold any type of data. String is an explicit declaration for holding string data only.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With