Chit Khine Chit Khine - 23 days ago 8
C# Question

How can i initiate an anonymous type without any value in c#?

I have one anonymous type which is an anonymous object of new {string a, string b}

var myObject = select new {
a = "a",
b = "b"
}


I would like to initialize that object without having to input any info.

For eg.

Anonymouse{string, string} myObject = new Anonymous;


I am stuck on this and would like to receive some help.

Answer

Anonymous types contain read-only properties. Therefore, if you want your object to contain properties, it is required to initialize your properties when you create them as they cannot be modified.

As mentioned here:

Anonymous types contain one or more public read-only properties.

Think of an anonymous type as a way to save on typing of defining an entire class (syntactic sugar). If you create an anonymous type without putting any info into it like the following:

var myObject = new {}

Behind the scenes the compiler create the following type:

class __Anonymous
{
    public Anonymous() {}
    public override bool Equals(object o) { … }
    public override int GetHashCode() { … }
}

However, you cannot add properties later, which is why you need to initialize your properties when you create the anonymous type.