As I understand it, properties can not return references, and since structs are value types, there’s no way to return a reference to a struct via properties, which would enable:
public struct SomeStruct
{
public int SomeMember { get; set; }
}
class foo
{
private SomeStruct bar;
public SomeStruct Bar{ get { return bar; } set { bar = value; } }
}
//Somewhere else
foo f = new foo();
f.Bar.SomeMember = 42; //Error, this doesn't work
Will I have to resort to setMemberOfSomeStruct() or is there another way?
edit: Specifically, I want to avoid having to call new for structs like these all the time. I know that with an constructor SomeStruct(int), this would work:
f.Bar = new SomeStruct(42); //ugh
Make your
structimplementations immutable and do this:Immutable structs help preserve the value type semantics that are expected.
If you don’t make it immutable, then the above code is still the only way to get this to work.
Alternatively, but not much nicer looking, expose a method on the class to set the class’s copy of
SomeStruct:I only offer this for completeness, I’d still go down the immutability route as there is consensus regarding “mutable structs are evil”. Property getters is one gotcha, as is casting to interfaces – immutable structs solve these.
There is also another facetious point to make – don’t assume that performance problems exist before performance problems actually exist. A
classdefinition might be just as fast as astructfor the style of use you get from it. Profiling is king here.