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"
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" };
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.