Is it same or any difference between Implicitly Typed and Anonymous Type.If it is different so What is the main difference between Implicitly Typed and Anonymous Type?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Generic Generics in Managed C++
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
There is a huge difference:
Implicitly typed (local) variables, are variables which type is not explicitly given:
Now,
i
is implicitly of typeStringBuilder
- a named type.Anonymous types on the other side do not have a name, they are anonymous:
x is now of an anonymous type, with a read-only property
Foo
.From Implicitly Typed Local Variables (C# Programming Guide):
Also:
There is a key relation between anonymous types and implicitly typed variables:
There are few fundamental differences between these
They are effectively class types with nothing other then read-only properties. No Methods no events. They cannot be accessed/declared outside the local scope. E.g if defined inside a method they cannot be accessed outside that method.
We can use
var
as an implicit type. This effectively means that the type of whatever is on the right side of expression will be assigned to this var by the compiler. These cannot be null.There are some difference between them
We can know which type of datatype or class assign to var
we can use implicitly typed in another scope also.
when we are not sure about which type of class assigned to var
Anonymous variable is used only in the scope where it was declared. but can't use in another scope and can't write in return statement of method.
Generally Anonymous used in Linq statement.
Anonymous type can be used only in the scope where it was declared. So you can use it to local tasks and can't use it in the outer scope.
The anonymous types was introduced to use with linq to achive an easy grouping and transformations. The main goal is avoid an explicit type declaration which will used in the single scope.
So a new anonymous type is declared and you can use it in the same context but can't send to the boundaries of the current scope as a strongly typed object
but you can use it locally without any restrictions
And the implicitly typed variables on the other hand is used to allow you to use object of an anonymous type. Compilator will investigate your code and put real type instead of the var keyword.
compilator will generate an anonymous type "{Name = "a";}" and use it to replace var in your code.