Eels Fan
Eels Fan

Reputation: 2063

Dynamic syntax in C#

Recently, I've come across C# examples that use a syntax that looks like the following:

var result = new { prop1 = "hello", prop2 = "world", prop3 = "." };

I really like it. It looks like JSON a bit. However, I don't know what this syntax is called. For that reason, I'm not sure how to learn more about it. I'm really interested in trying to figure out how to define arrays of objects within a result. For instance, what if I wanted to return an array of items for prop3? What would that look like? What is this syntax called?

Upvotes: 20

Views: 869

Answers (5)

jorgehmv
jorgehmv

Reputation: 3713

it's called anonymous types. For returning an array of objects in prop3 you would write

var result = new { prop1 = "hello", prop2 = "world", prop3 = new[] { "h", "e", "l", "l", "o" } };

I'm using strings but is the same for any type of object:

var result = new { prop1 = "hello", prop2 = "world", prop3 = new[] { new YourType(), new YourType(), new YourType() } };

Note that the type of the objects in the array is not necessary in the declaration of the array; you don't need to write new YourType[], the compiler don't need it and IMO it's cleaner to simply use new[]

Upvotes: 5

Jeremy Wiggins
Jeremy Wiggins

Reputation: 7299

A couple of newish features here:

  1. An object initializer - let's you set properties on an object without constructing it first.

  2. An implicitly typed variable - using the var keyword will let the compiler figure out what type the object is.

You can combine these features to form an anonymous type. Since you don't have to declare or construct the type at compile time, you can declare this object and the compiler will make the appropriate type and construct it for you in IL.

Upvotes: 3

user2985029
user2985029

Reputation:

The following code is an example of an anonymous type using an object initialiser

var result = new { prop1 = "hello", prop2 = "world", prop3 = "." };

for more information see Anonymous Types (C# Programming Guide) and Object and Collection Initializers (C# Programming Guide)

Upvotes: 2

John Koerner
John Koerner

Reputation: 38077

This is referred to as Anonymous Types in C#.

To return an array, you can simply inline it:

var result = new { prop1 = "hello", prop2 = "world", prop3 = new int[] {1,2,3} };

Or declare it beforehand and use it:

int[] array = new int[] {1,2,3};
var result = new { prop1 = "hello", prop2 = "world", prop3 = array};

Upvotes: 25

Blake
Blake

Reputation: 2117

These are object and collection initializers. See http://msdn.microsoft.com/en-us/library/vstudio/bb384062.aspx.

Upvotes: 2

Related Questions