Non-read only alternative to anonymous types

Superbest picture Superbest · Jan 28, 2012 · Viewed 22.9k times · Source

In C#, an anonymous type can be as follows:

method doStuff(){
     var myVar = new {
         a = false, 
         b = true
     }

     if (myVar.a) 
     {
         // Do stuff             
     }
}

However, the following will not compile:

method doStuff(){
     var myVar = new {
         a = false, 
         b = true
     }

     if (myVar.a) 
     {
         myVar.b = true;
     }
}

This is because myVar's fields are read-only and cannot be assigned to. It seems wanting to do something like the latter is fairly common; perhaps the best solution I've seen is to just define a struct outside the method.

However, is there really no other way to make the above block work? The reason it bothers me is, myVar is a local variable of this field, so it seems like it should only be referred to inside the method that uses it. Besides, needing to place the struct outside of the method can make the declaration of an object quite far from its use, especially in a long method.

Put in another way, is there an alternative to anonymous types which will allow me to define a "struct" like this (I realize struct exists in C# and must be defined outside of a method) without making it read-only? If no, is there something fundamentally wrong with wanting to do this, and should I be using a different approach?

Answer

Jon Skeet picture Jon Skeet · Jan 28, 2012

No, you'll have to create your own class or struct to do this (preferrably a class if you want it to be mutable - mutable structs are horrible).

If you don't care about Equals/ToString/GetHashCode implementations, that's pretty easy:

public class MyClass {
    public bool Foo { get; set; }
    public bool Bar { get; set; }
}

(I'd still use properties rather than fields, for various reasons.)

Personally I usually find myself wanting an immutable type which I can pass between methods etc - I want a named version of the existing anonymous type feature...