2

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?

NightRaven
  • 401
  • 3
  • 17

2 Answers2

8

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 };
Timothy Shields
  • 75,459
  • 18
  • 120
  • 173
pascalhein
  • 5,700
  • 4
  • 31
  • 44
  • 1
    @TimothyShields Hmm, `readonly` isn't too exact either. They are properties with a getter but no setter, so signature like `public type var1 { get { ... } }`. – Jeppe Stig Nielsen Jul 12 '13 at 22:28
  • @JeppeStigNielsen I know - I was going for closer-to-correct without drastically changing csharpler's answer. Without the `readonly` hint, someone might think that these are mutable fields. – Timothy Shields Jul 12 '13 at 22:33
1

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.

recursive
  • 83,943
  • 34
  • 151
  • 241