How can a dynamic be used as a generic? - c#

How can I use a dynamic as a generic?
This
var x = something not strongly typed;
callFunction<x>();
and this
dynamic x = something not strongly typed;
callFunction<x>();
both produce this error
Error 1 The type or namespace name 'x'
could not be found (are you missing a using directive or an assembly reference?)
What can I do to x to make it legitimate enough to be used in <x>?

You could use type inference to sort of trampoline the call:
dynamic x = something not strongly typed;
CallFunctionWithInference(x);
...
static void CallFunctionWithInference<T>(T ignored)
{
CallFunction<T>();
}
static void CallFunction<T>()
{
// This is the method we really wanted to call
}
This will determine the type argument at execution time based on the execution-time type of the value of x, using the same kind of type inference it would use if x had that as its compile-time type. The parameter is only present to make type inference work.
Note that unlike Darin, I believe this is a useful technique - in exactly the same situations where pre-dynamic you'd end up calling the generic method with reflection. You can make this one part of the code dynamic, but keep the rest of the code (from the generic type on downwards) type-safe. It allows one step to be dynamic - just the single bit where you don't know the type.

It's hard to tell what exactly are you trying to do. But if you want to call a generic method with a type parameter that is the same as some object, you can't do that directly. But you can write another method that takes your object as a parameter, let the dynamic infer the type and then call the method you want:
void HelperMethod<T>(T obj)
{
CallFunction<T>();
}
…
dynamic x = …;
HelperMethod(x);

You can't. The whole point of generics is compile-time safety which means that they must be known at compile-time. And the whole point of dynamics is that you don't need to know the exact type at compile time and use runtime dispatching => it's the absolutely exact opposite of generics. So don't waste your time => once you get the dynamic/reflection path you can forget about generics and compile-time safety. You will have to walk that path till the end.
So to answer your question:
What can I do to x to make it legitimate enough to be used in ?
The only thing you could do is to use a type that is known at compile-time, otherwise you cannot use generics.

You get that error because x is not a type. You need to specify a type as a type parameter.
In fact, you can use dynamic as a type parameter if you use it correctly:
var dict = new Dictionary<string, dynamic>();
dict.Add("Item1", 123);
dict.Add("Item2", "Blah");
This compiles and runs just fine.

The quickest way to make this work is to make your anonymous type a real type.
So instead of
var x = new { Value = "somevalue", Text = "sometext" };
You need to do
class MyClass
{
string Text, Value;
}
....
var x = new MyClass() { Value = "somevalue", Text = "sometext" };
//this should work now
callFunction<MyClass>(x);

You should be able to call the function like this
callFunction<dynamic>();
If your function is defined as
public void callFunction<T>(T arg) {
...
}
You can simply call it with
callFunction(x);
C# is able to infer generic type parameters in many situations.

Related

Why does a method that returns a type result in an implicit typing of dynamic?

In the following code snippet why does the implicitly typed variable be determined as a dynamic instead of the method's return type of FluentClass?
public static class DynamicTest
{
public class FluentClass
{
public FluentClass SomeMethod(dynamic arg)
{
return this;
}
}
public static void Main()
{
dynamic data = new { Data = 1 };
var fluentClass = new FluentClass();
// fluentClass variable is typed FluentClass
var methodResult = fluentClass.SomeMethod(data);
// methodResult variable is typed dynamic
}
}
Why does a method that returns a type result in an implicit typing of dynamic?
Because that's the best the compiler can do, given the information it has.
The reason methodResult is dynamic is that the entire expression used to initialize it is dynamic. And that's the case, because data is dynamic.
When you use dynamic, you're telling the compiler to not resolve types at compiler time. Instead, they should be resolved according to the normal compiler rules, but at run-time.
The fluentClass variable could hold some implementation of FluentClass that contains an overload that matches the run-time type of the argument data. In that case, a different implementation of SomeMethod() could be called, returning a different type.
You've told the compiler to defer type resolution to run-time, so it can't force things back into a strongly-typed context unless you tell it explicitly what type things are. In your example, it can't, so the type remains dynamic.
Note that you might have thought that the compiler would identify the one overload you've provided, based on its parameter type of dynamic. But that's not how dynamic works. The dynamic parameter affects only the implementation of the method, i.e. the code in its body. As far as calling the method goes, the parameter is essentially object. It's just that when the parameter value is used in the method body, it has the features of dynamic.
Another way to think of dynamic is that it accepts any object as input (like object), but then allows you to use any member of that object that you believe exists (if it doesn't exist an exception will be thrown at run-time). Using dynamic defers the compiler logic downstream, i.e. for the output of any usages of the dynamic variable, but doesn't affect the input, i.e. the assignment of that variable.
Note also that even if the method call is completely unambiguous, e.g. a static method where there's only one method with that name, you'll still get a dynamic result. Once you start using dynamic, it sticks with you until you provide an explicit cast to get back to a known type.
Related reading:
Very similar to your question, if not actually duplicates:
Why does a method invocation expression have type dynamic even when there is only one possible return type?
Why does this method keep returning dynamic despite the return type in the signature?
Why doesn't this string.Format() return string, but dynamic?
More general discussion of dynamic:
What is the 'dynamic' type in C# 4.0 used for?
C# 4: Real-World Example of Dynamic Types

Dynamic casting

Why do the two last lines not work and give me
The type or namespace name 'myType' could not be found
Type myType = this.GetType();
bool test = obj is myType;
var p = (myType)obj;
You need to do:
bool test = myType.IsInstanceOfType(obj);
or
bool test = myType.IsAssignableFrom(obj.GetType());
// var p = Convert.ChangeType(obj, myType); - update: this is not what the OP asked
For the second one, you can't "cast" an expression to a type which is not known at compile time. The point of casting is to reference the members of that type natively. If you don't know what the type is at compile type (because you are using .GetType()), then there is no point casting, and indeed it's impossible.
C# is a statically typed language, which means types must be known at compile time. The var keyword just means "Figure out what this type should be automatically (through inference) at compile time".
Any cast or type-check has to be against a static type. You are actually trying to use an instance of an object of type Type that describes a type. That instance is provided to you by .NET Reflection.
Once you are working with an object of a type derived at runtime you have to use reflection for all operations on that instance. For example, you can do something like this:
bool test = myType.IsInstanceOfType(obj);
bool test = typeof(obj).IsAssignableFrom(myType); // Good for checking if a type implements an interface
For your second line, you can use an object reference to hold any type:
object p = obj;
The type of object being cast to must be determined at compile time in C#. You're trying to make a cast based on the runtime type of the object which is incompatible with this notion. Hence you get this error.
Can you give us an example of what you want to do with p? There is likely a cleaner way.
If you want to know if an object is an instance or implementation of a Type at runtime, you need to do:
Type thisType = this.GetType();
Type objType = obj.GetType();
if(objType.IsAssignableFrom(type))
{
// do your stuff
}
From there, there is no way to cast an object to a runtime type since the compiler need that information at compile time. However, if you are using C# 4, you can use the dynamic type.
Type thisType = this.GetType();
Type objType = obj.GetType();
if(objType.IsAssignableFrom(type))
{
dynamic dynObj = obj;
dynObj.CallWhateverIWant();
}
However, looking at your code, there is obviously a better way to do want you want to do. Maybe you could implement some kind of interface, common to both classes and use functions from that interface at compile time.
I don't have a Visual Studio ready at the moment and this isn't something I need to do often, but for the second line I think it should look like this:
bool test = obj is typeof(this);
The third line is not possible unless you have a limited set of possible types you can switch on.
the is operator works on classes, not objects of type Type
If you want to do this sort of thing, use the dynamic keyword
http://msdn.microsoft.com/en-us/library/dd264736.aspx

Is the C# compiler unable to infer method type parameters by expected return type?

This seems odd to me, but I remember a thread where Eric Lippert commented on the inability (by design, or at least convention, I think) of C# to overload methods based on return type, so perhaps it's in some convoluted way related to that.
Is there any reason this does not work:
public static T Test<T>() where T : new()
{
return new T();
}
// Elsewhere
SomeObject myObj = Test();
But this does:
var myObj = Test<SomeObject>();
From a certain perspective, they're both fine, in that you're not Repeating Yourself (in a very small way), but is this just a different pass of the compiler?
First off, this is "overloading based on return type":
void M(int x){...}
int M(int x){...}
string M(int x){...}
The declarations are not legal; you can't overload a method based on return type because the return type is not part of the signature, and the signature has to be unique.
What you are talking about is method type inference based on the method's return type. We don't support that either.
The reason is because the return type might be what you are trying to figure out.
M(Test());
What's the return type of Test? That depends on which overload of M we choose. What overload of M do we choose? That depends on the return type of Test.
In general, C# is designed so that every subexpression has a type, and the types are worked out from the "inside" towards the "outside", not from the outside to the inside.
The notable exceptions are anonymous functions, method groups, and null:
M(x=>x+1)
What's the type of x=>x+1? It depends on which overload of M is called.
M(N); // N is a method group
what's the type of N? Again, it depends on which overload of M is called.
And so on. In these cases we do reason from "outside" to "inside".
Type inference involving lambdas is extremely complicated and was difficult to implement. We don't want to have that same complication and difficulty throughout the compiler.
Except for typeless expressions (null, method groups, and lambda expressions), the type of an expression must be statically determinable by the expression itself, regardless of context.
In other words, the type of an expression Test() cannot depend on what you're assigning it to.
Check C# Language Specification §7.5.2, the declaring type of a variable is not an attestation for type inference, and obviously it shouldn't be. Consider the following code:
Base b = Test<Derived>();
Derived d = Test<Derived>();
The return type of the method probably differs from the declaring type of the variable, since we have implicit convert in C#.
Type inference by the compiler doesn't use the "expected type" of an assignment as part of the logic.
So, the "scope of consideration" for type inference is not this:
SomeObject myObj = Test();
but this:
Test();
And, there are no clues here as to the expected type.
If you want an example of why the type of an expression needs to be able to be determined by the expression itself, consider the following two cases:
We don't use the return value at all - we're just calling the method for its side-effects.
We pass the return value directly into an overloaded method
Using the "expected type" of the return value when it comes to generic type resolution would introduce a whole whack of additional complexity into the compiler, and all you've gained is that sometimes you need to explicitly specify the type and sometimes you don't, and whether you need to or not can change based on unrelated changes elsewhere in the code.

Why it isn't possible to declare a method parameter as var type

I wonder why it is not possible a method parameter as var type like
private void myMethod(var myValue) {
// do something
}
You can only use var for variables inside the method body. Also the variable must be assigned at declaration and it must be possible to deduce the type unambiguously from the expression on the right-hand side.
In all other places you must specify a type, even if a type could in theory be deduced.
The reason is due to the way that the compiler is designed. A simplified description is that it first parses everything except method bodies and then makes a full analysis of the static types of every class, member, etc. It then uses this information when parsing the method bodies, and in particular for deducing the type of local variables declared as var. If var were allowed anywhere then it would require a large change to the way the compiler works.
You can read Eric Lippert's article on this subject for more details:
Why no var on fields?
Because the compiler determines the actual type by looking at the right hand side of the assignment. For example, here it is determined to be a string:
var s = "hello";
Here it is determined to be Foo:
var foo = new Foo();
In method arguments, there is no "right hand side of the assignment", so you can't use var.
See the posting by Eric Lippert about why var is not allowed on fields, which also contains the explanation why it doesn't work in method signatures:
Let me give you a quick oversimplification of how the C# compiler works. First we run through every source file and do a "top level only" parse. That is, we identify every namespace, class, struct, enum, interface, and delegate type declaration at all levels of nesting. We parse all field declarations, method declarations, and so on. In fact, we parse everything except method bodies; those, we skip and come back to them later.
[...]
if we have "var" fields then the type of the field cannot be determined until the expression is analyzed, and that happens after we already need to know the type of the field.
Please see Juliet's answer for a better answer to this question.
Because it was too hard to add full type inference to C#.
Other languages such as Haskell and ML can automatically infer the most general type without you having to declare it.
The other answers state that it's "impossible" for the compiler to infer the type of var but actually it is possible in principle. For example:
abstract void anotherMethod(double z, double w);
void myMethod<T>(T arg)
{
anotherMethod(arg, 2.0); // Now a compiler could in principle infer that arg must be of type double (but the actual C# compiler can't)
}
Have "var" method parameters is in principle the same thing as generic methods:
void myMethod<T>(T arg)
{
....
}
It is unfortunate that you can't just use the same syntax for both but this is probably due to the fact that that C#'s type inference was added only later.
In general, subtle changes in the language syntax and semantics can turn a "deterministic" type inference algorithm into an undecidable one.
ML, Haskell, Scala, F#, SML, and other languages can easily figure out the type from equivalent expressions in their own language, mainly because they were designed with type-inference in mind from the very start. C# wasn't, its type-inference was tacked on as a post-hoc solution to the problem of accessing anonymous types.
I speculate that true Hindley-Milner type-inference was never implemented for C# because its complicated to deduce types in a language so dependent on classes and inheritance. Let's say I have the following classes:
class Base { public void Print() { ... } }
class Derived1 : Base { }
class Derived2 : Base { }
And now I have this method:
var create() { return new Derived1(); }
What's the return type here? Is it Derived1, or should it be Base? For that matter, should it be object?
Ok, now lets say I have this method:
void doStuff(var someBase) { someBase.Print(); }
void Main()
{
doStuff(new Derived1());
doStuff(new Derived2()); // <-- type error or not?
}
The first call, doStuff(new Derived1()), presumably forces doStuff to the type doStuff(Derived1 someBase). Let's assume for now that we infer a concrete type instead of a generic type T.
What about the second call, doStuff(new Derived1())? Is it a type error, or do we generalize to doStuff<T>(T somebase) where T : Base instead? What if we made the same call in a separate, unreferenced assembly -- the type inference algorithm would have no idea whether to use the narrow type or the more genenarlized type. So we'd end up with two different type signatures based on whether method calls originate from inside the assembly or a foreign assembly.
You can't generalize wider types based on usage of the function. You basically need to settle on a single concrete type as soon as you know which concrete type is being pass in. So in the example code above, unless you explicitly cast up to the Base type, doStuff is constrained to accept types of Derived1 and the second call is a type error.
Now the trick here is settling on a type. What happens here:
class Whatever
{
void Foo() { DoStuff(new Derived1()); }
void Bar() { DoStuff(new Derived2()); }
void DoStuff(var x) { ... }
}
What's the type of DoStuff? For that matter, we know based on the above that one of the Foo or Bar methods contain a type error, but can you tell from looking which has the error?
Its not possible to resolve the type without changing the semantics of C#. In C#, order of method declaration has no impact on compilation (or at least it shouldn't ;) ). You might say instead that the method declared first (in this case, the Foo method) determines the type, so Bar has an error.
This works, but it also changes the semantics of C#: changes in method order will change the compiled type of the method.
But let's say we went further:
// Whatever.cs
class Whatever
{
public void DoStuff(var x);
}
// Foo.cs
class Foo
{
public Foo() { new Whatever().DoStuff(new Derived1()); }
}
// Bar.cs
class Bar
{
public Bar() { new Whatever().DoStuff(new Derived2()); }
}
Now the methods is being invoked from different files. What's the type? Its not possible to decide without imposing some rules on compilation order: if Foo.cs gets compiled before Bar.cs, the type is determined by Foo.cs.
While we can impose those sorts of rules on C# to make type inference work, it would drastically change the semantics of the language.
By contrast, ML, Haskell, F#, and SML support type inference so well because they have these sorts of restrictions: you can't call methods before they're declared, the first method call to inferred functions determines the type, compilation order has an impact on type inference, etc.
The "var" keyword is used in C# and VB.NET for type inference - you basically tell the C# compiler: "you figure out what the type is".
"var" is still strongly typed - you're just too lazy yourself to write out the type and let the compiler figure it out - based on the data type of the right-hand side of the assignment.
Here, in a method parameter, the compiler has no way of figuring out what you really meant. How? What type did you really mean? There's no way for the compiler to infer the type from the method definition - therefore it's not a valid statement.
Because c# is type safe and strong type language. At any place of your program compiler always knows the type of argument you are using. var keyword was just introduced to have variables of anonymus types.
Check dynamic in C# 4
Type inference is type inference, either in local expressions or global / interprocedural. So it isn't about "not having a right hand side", because in compiler theory, a procedure call is a form of "right hand side".
C# could do this if the compiler did global type inference, but it does not.
You can use "object" if you want a parameter that accepts anything, but then you need to deal with the runtime conversion and potential exceptions yourself.
"var" in C# isn't a runtime type binding, it is a compile time feature that ends up with a very specific type, but C# type inference is limited in scope.

What's the difference between dynamic (C# 4) and var?

I had read a ton of articles about that new keyword that is shipping with C# v4, but I couldn't make out the difference between a "dynamic" and "var".
This article made me think about it, but I still can't see any difference.
Is it that you can use "var" only as a local variable, but dynamic as both local and global?
Could you show some code without dynamic keyword and then show the same code with dynamic keyword?
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.
Variables declared with var are implicitly but statically typed. Variables declared with dynamic are dynamically typed. This capability was added to the CLR in order to support dynamic languages like Ruby and Python.
I should add that this means that dynamic declarations are resolved at run-time, var declarations are resolved at compile-time.
I am going to explain difference between dynamic and var.
dynamic d1;
d1 = 1;
d1 = "http://mycodelogic.com";
This will work. compiler can re-create the type of dynamic variable.
first it create type as integer and after that compiler will recreate type as string but in case of var
var v1; // Compiler will throw error because we have to initialized at the time of declaration
var v2 = 1; // Compiler will create v1 as **integer**
v2 = "Suneel Gupta"; // Compiler will throw error because, compiler will not recreate the type of variable
When using the ‘var’ keyword, the type is decided by the compiler at compile time, whereas when using the ‘dynamic’ keyword, the type is decided by the runtime.
‘var’ keyword, a strongly implicitly typed local variable for which the compiler is able to determine the type from the initialization expression - very useful when doing LINQ programming.
Compiler doesn't have any information about the dynamic type of variable. so compiler will not show any intelligence .compiler has all information about the stored value of var type so compiler will show intelligence.dynamic type can be passed as function argument and function also can return object typeButvar type can not be passed as function argument and function can not return object type. This type of variable can work in the scope where it defined.
var implies that static type checking (early binding) is applied. dynamic implies that dynamic type checking (late binding) is applied. In terms of the code, condsider the following:
class Junk
{
public void Hello()
{
Console.WriteLine("Hello");
}
}
class Program
{
static void Main(String[] args)
{
var a = new Junk();
dynamic b = new Junk();
a.Hello();
b.Hello();
}
}
If you compile this and inspect the results with ILSpy, you will find that the compiler has added some late binding code which will handle the call to Hello() from b, whereas becuase early binding was applied to a, a is able to call Hello() directly.
e.g. (ILSpy disassembly)
using System;
namespace ConsoleApplication1
{
internal class Junk
{
public void Hello()
{
Console.WriteLine("Hello");
}
}
}
using Microsoft.CSharp.RuntimeBinder;
using System;
using System.Runtime.CompilerServices;
namespace ConsoleApplication1
{
internal class Program
{
[CompilerGenerated]
private static class <Main>o__SiteContainer0
{
public static CallSite<Action<CallSite, object>> <>p__Site1;
}
private static void Main(string[] args)
{
Junk a = new Junk(); //NOTE: Compiler converted var to Junk
object b = new Junk(); //NOTE: Compiler converted dynamic to object
a.Hello(); //Already Junk so just call the method.
//NOTE: Runtime binding (late binding) implementation added by compiler.
if (Program.<Main>o__SiteContainer0.<>p__Site1 == null)
{
Program.<Main>o__SiteContainer0.<>p__Site1 = CallSite<Action<CallSite, object>>.Create(Binder.InvokeMember(CSharpBinderFlags.ResultDiscarded, "Hello", null, typeof(Program), new CSharpArgumentInfo[]
{
CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null)
}));
}
Program.<Main>o__SiteContainer0.<>p__Site1.Target(Program.<Main>o__SiteContainer0.<>p__Site1, b);
}
}
}
The best thing you can do to discover the difference is to write yourself a little console app like this one, and test it yourself with ILSpy.
One big difference - you can have a dynamic return type.
dynamic Foo(int x)
{
dynamic result;
if (x < 5)
result = x;
else
result = x.ToString();
return result;
}
Here is simple example which demonstrates difference between Dynamic (4.0) and Var
dynamic di = 20;
dynamic ds = "sadlfk";
var vi = 10;
var vsTemp= "sdklf";
Console.WriteLine(di.GetType().ToString()); //Prints System.Int32
Console.WriteLine(ds.GetType().ToString()); //Prints System.String
Console.WriteLine(vi.GetType().ToString()); //Prints System.Int32
Console.WriteLine(vsTemp.GetType().ToString()); //Prints System.String
**ds = 12;** //ds is treated as string until this stmt now assigning integer.
Console.WriteLine(ds.GetType().ToString()); **//Prints System.Int32**
**vs = 12**; //*Gives compile time error* - Here is the difference between Var and Dynamic. var is compile time bound variable.
Shiva Mamidi
var is just a shorthand for a normal type declaration, where you let the compiler guess the correct type.
dynamic is a new (static) type, where all checks are done at runtime, not by the compiler.
This is a nice youtube video which talks about var VS Dynamic with practical demonstration.
Below is a more detailed explanation with snapshot.
Var is early binded (statically checked) while dynamic is late binded (dynamically evaluated).
Var keyword looks at your right hand side data and then during compile time it decides the left hand data type.In other words var keyword just saves you typing lot of things. Have a look at the below image where when we have given string data and x variable shows string data type in my tool tip.
On the other hand dynamic keyword is for completely different purpose. Dynamic objects are evaluated during runtime. For instance in the below code the "Length" property exists or not is evaluated during runtime.I have purposely typed a small "l" , so this program compiled fine but when it actually executed it throwed up a error when the "length" property was called ( SMALL "l").
The type of a variable declared with var is determined by the compiler, it is a shortcut to specifying the type's name, nothing more.
However dynamic is determined at runtime, the compiler has no idea of the actual type, and all method/field/property accesses with that variable will be worked out at runtime.
Here are the differences
var is statically typed (compile time), dynamic is dynamically typed (run time)
A variable declared as var can only be used locally , dynamic
variables can be passed in as params to function (function signature
can define a param as dynamic but not var).
with dynamic the resolution of the properties happens at runtime and
thats not the case with var which means at compile time any variable
declared as dynamic can call a method which may or maynot exist and
so the compiler would not throw an error.
Type casting with var not possible but with dynamic its possible (you can cast an object as dynamic but not as var).
Arun Vijayraghavan
dynamic variable and var variable both can store any type of value but its required to initialize 'var' at the time of declaration.
Compiler doesn't have any information about the 'dynamic' type of variable.
var is compiler safe i.e compiler has all information about the stored value, so that it doesn't cause any issue at run-time.
Dynamic type can be passed as function argument and function also can return it.
Var type can not be passed as function argument and function can not return object type. This type of variable can work in the scope where it defined.
In case of dynamic Casting is not require but you need to know the property and methods related to stored type , while for var No need to cast because compiler has all information to perform operation.
dynamic: Useful when coding using reflection or dynamic language support or with the COM objects, because we require to write less amount of code.
var: Useful when getting result out of the linq queries. In 3.5 framework it introduce to support linq feature.
Reference : Counsellingbyabhi
Var and dynamic define type.
var at the compile time while dynamic are at run time.
in the var declaration and initialization both are mandatory like constant variable while
in dynamic initialization can be at run time like readonly variables.
in var type whatever type are decided at the time initialization can not change next but
dynamic can adopt any type even user define datatype also.
Do not confuse dynamic and var.
Declaring a local variable using var is just a syntactical shortcut that has the compiler infer the specific data type from an expression.
The var keyword can be used only for declaring local variables inside a method while the dynamic keyword can be used for local variables, fields, and arguments. You cannot cast an expression to var, but you can cast an expression to dynamic. You must explicitly initialize a variable declared using var while you do not have to initialize a variable declared with dynamic.
The Var(Implicit typed local variable) keyword is used to define local variables.In case of Var , the underlying data type is determined at compile time itself based on the initial assignment.Once the initial assignment has been made with Var type , then it will become strongly typed.If you try to store any incompatible value with the Var type it will result in compile time error.
Example:
Var strNameList=new List<string>(); By using this statement we can store list of names in the string format.
strNameList.add("Senthil");
strNameList.add("Vignesh");
strNameList.add(45); // This statement will cause the compile time error.
But in Dynamic type, the underlying type is determined only at run time.Dynamic data type is not checked at compile time and also it is not strongly typed.We can assign any initial value for dynamic type and then it can be reassigned to any new value during its life time.
Example:
dynamic test="Senthil";
Console.Writeline(test.GetType()) // System.String
test=1222;
Console.Writeline(test.GetType()) // System.Int32
test=new List<string>();
Console.Writeline(test.GetType()) //System.Collections.Generic.List'1[System.String]
It doesn't provide IntelliSense support also.It doesn't give better support when we give work with linq also.Because it doesn't support lambda expressions ,extension methods and anonymous methods.

Categories

Resources