tags:

views:

118

answers:

2

I'm using var abc = new { id = 0 }; in my C# code without knowing what type it exactly is!

Is is simply called an object? Is it a particular type of object?

I want to know coz I don't know how to add fields to this kind of object

Quick example: I have var abc = new { id = 0 }; and I want to add to abc the field name = "david"

+1  A: 

It creates anonymous class object with one field called id. Look on msdn for details. Once you create object it cannot be extended.

This what this class looks like when open with .net Reflector

[CompilerGenerated, DebuggerDisplay(@"\{ id = {id} }", Type="<Anonymous Type>")]
internal sealed class <>f__AnonymousType0<<id>j__TPar>
{
    // Fields
   [DebuggerBrowsable(DebuggerBrowsableState.Never)]
   private readonly <id>j__TPar <id>i__Field;

   // Methods
   [DebuggerHidden]
   public <>f__AnonymousType0(<id>j__TPar id);

   [DebuggerHidden]
   public override bool Equals(object value);

   [DebuggerHidden]
   public override int GetHashCode();

   [DebuggerHidden]
   public override string ToString();

   // Properties
  public <id>j__TPar id { get; }
}

So its compiled to regular class the basic difference is that it cannot be used outside of method scope.

jethro
+9  A: 

It is an anonymous type, that is, it does not have a type that you can use in code (though the compiler generates one).

MSDN says:

The type name is generated by the compiler and is not available at the source code level.

If you want to add a property, you can simply do so:

var abc = new { id = 0, name = "david" };
Oded
Can the downvote please explain why?
Oded
@Oded: I can only guess, but perhaps because it's not really correct. It *does* have an explicit type, it's just that the type is created by the compiler and doesn't have a name (other than internally for the compiler).
Guffa
@Guffa - possibly... I amended my answer to be more correct.
Oded