In C#, an anonymous type can be as follows:
method doStuff(){
var myVar = new {
a = false,
b = true
}
if (myVar.a)
{
For the above types of operation, you should define your own mutable STRUCT. Mutable structs may pose a headache for compiler writers like Eric Lippert, and there are some unfortunate limitations in how .net handles them, but nonetheless the semantics of mutable "Plain Old Data" structs (structs in which all fields are public, and the only public functions which write this
are constructors, or are called exclusively from constructors) offer far clearer semantics than can be achieved via classes.
For example, consider the following:
struct Foo { public int bar; ...other stuff; } int test(Actionproc1, Action proc2) { foo myFoos[] = new Foo[100]; proc1(myFoos); myFoos[4].bar = 9; proc2(myFoos[4]); // Pass-by-value return myFoos[4].bar; }
Assuming there's no unsafe code and that the passed-in delegates can be called and will return in finite time, what will test()
return? The fact that Foo
is a struct with a public field bar
is sufficient to answer the question: it will return 9, regardless of what else appears in the declaration of Foo
, and regardless of what functions are passed in proc1
and proc2
. If Foo
were a class, one would have to examine every single Action
and Action
that exists, or will ever exist, to know what test()
would return. Determining that Foo
is a struct with public field bar
seems much easier than examining all past and future functions that might get passed in.
Struct methods which modify this
are handled particularly poorly in .net, so if one needs to use a method to modify a struct, it's almost certainly better to use one of these patterns:
myStruct = myStruct.ModifiedInSomeFashion(...); // Approach #1 myStructType.ModifyInSomeFashion(ref myStruct, ...); // Approach #2
than the pattern:
myStruct.ModifyInSomeFashion(...);
Provided one uses the above approach to struct-modifying patterns, however, mutable structs have the advantage of allowing code which is both more efficient and easier to read than immutable structs or immutable classes, and is much less trouble-prone than mutable classes. For things which represent an aggregation of values, with no identity outside the values they contain, mutable class types are often the worst possible representation.