Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 973
Chit Khine Avatar asked Jan 17 '26 23:01

Chit Khine


1 Answers

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.

like image 107
Jesse Good Avatar answered Jan 19 '26 14:01

Jesse Good



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!