benj
benj

Reputation: 417

new keyword without class name in c#

While going through the ASP.NET MVC docs I see this idiom being used alot:

new { foo = "bar", baz = "foo" }

Is this a Dictionary literal syntax? Is it a new class/struct with the type inferred by the called function definition? If it is how come the vars don't need a type definition, not even var?

Upvotes: 10

Views: 5105

Answers (3)

Tim M.
Tim M.

Reputation: 54387

This is an anonymous type.

Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to explicitly define a type first. The type name is generated by the compiler and is not available at the source code level. The type of each property is inferred by the compiler.

http://msdn.microsoft.com/en-us/library/bb397696.aspx

  • Anonymous types are strongly typed. From the perspective of the common language runtime, an anonymous type is no different from any other reference type.

  • If two or more anonymous types in the same assembly have the same number and type of properties, in the same order, the compiler treats them as the same type. They share the same compiler-generated type information.

  • Anonymous types should not be passed between assemblies or even as return values from methods (possible, but rarely, rarely advisable).

  • Anonymous types are a convenience mechanism, e.g. when working with LINQ, such as the following projection:

LINQ Example

var result = myEnumerable.Select( o => new { foo = o.Foo, bar = o.Bar } );
// "result" is an enumerable of a new anonymous type containing two properties

Other Questions

Is this a Dictionary literal syntax?

No, though there are many similarities. ASP .Net MVC uses RouteValueDictionary and anonymous types to represent the same information in many method overloads.

how come the vars don't need a type definition, not even var?

Value types are inferred, though inference is not always possible: http://msdn.microsoft.com/en-us/library/bb531357.aspx (VB version, if someone knows the URL of the c# equivalent please update)

Upvotes: 14

Shyju
Shyju

Reputation: 218852

This is anonymous type. That means it is returning something which has a foo property, a baz property both of string type.

Upvotes: 2

Kale McNaney
Kale McNaney

Reputation: 457

This is an anonymous type syntax. The type name is generated by the compiler and is not available at the source code level. The type of each property is inferred by the compiler.

Upvotes: 4

Related Questions