DotNet Pros & Cons Classes vs Anon Types vs Value Tuples - OperationCode/member_content GitHub Wiki
Pros and cons of the different strategies:
A class:
public class FooClass {
public string Str;
public int Integer;
}
...
var x = new FooClass {Str = "foo", Integer = 123};
Pros:
- Is super explicit and there can be no confusion
- Instances can be passed around everywhere
- Compiled retains all type info (so reflection can for example work)
- Helper methods can be added as needed (even as extension methods)
Cons:
- More typing
- Since there is a class, it can be reused elsewhere by someone else on your project which implicitly builds a dependency between their code and yours. You might want your objects to be single-use
An anonymous type:
var x = new { Str = "foo", Integer = 123};
Pros:
- Is super explicit and there can be no confusion
- Compiled retains all type info (so reflection can for example work)
- Way less typing
- Explicitly single use
Cons:
- Properties be accessed statically only within the scope that it was created (basically, you can’t return it or pass it into another method and have them use it without
dynamic
) - Can only be used with
var
- Is marked internal so can’t be used even dynamically outside the current assembly
A value tuple:
var x = (Str:"foo", Integer: 123)
Pros:
- Even less typing
- Explicitly single use
- Can be returned or passed into methods/other assemblies and referenced statically (see cons) Cons:
- Label names are compiled out. Reflection cannot be used to access the label names!
- Not Explicit! When returned from a method, labels are inferred from an attribute on the method, Therefore someone up the call chain can change the labels as they wish