NightRaven
NightRaven

Reputation: 401

what does this syntax mean? new { }

I stumbled upon this weird form of syntax in C#, and was trying to figure out what it means and how to use it. There doesn't seem to be any documentation on the net on this.

object data = new { var1 = someValue, var2 = anotherValue }

There are no errors with this syntax, so I assume it's something that C# allows. what does it mean?

Upvotes: 2

Views: 255

Answers (2)

pascalhein
pascalhein

Reputation: 5856

This is an anonymous type. It will basically work like a class:

class anonymous
{
    public readonly type var1; // "type" is the type of somevalue
    public readonly type var2; // "type" is the type of anothervalue
}

which is instantiated with

var data = new anonymous { var1 = somevalue, var2 = anothervalue };

Upvotes: 8

recursive
recursive

Reputation: 86134

That syntax creates an instance of an "anonymous type". It is still a statically typed object that is fully type safe, but you can add whatever properties you want at the time you create it.

There is more documentation here.

You can't use an anonymous type as a return type or declare a member field using one. You can't use one anywhere you have to provide the type name, since it doesn't have one.

Upvotes: 1

Related Questions