For a Unity3d game I’m working on, I have a situation where I want a read/writeable property with a trivial getter, but a setter which does some more work. My code looks like this:
// IColor.cs
interface IColor {
Color colorPainted { get; set; }
}
// Player.cs
public class Player : Monobehaviour, IColor {
// ...
public Color colorPainted {
get { }
set {
colorPainted = value;
// some other code
}
// ...
}
}
I’m not sure what to do about the get part, though. I can’t return colorPainted;, because that causes a stack overflow. The code as written won’t compile because I’m not returning a value.
I’m no C# wizard, but it seems like I’d need to have a _colorPainted backing variable, and provide access to that through the get and set. This seems kinda verbose, though — is there a better way to do it? In Objective-C, I’d simply leave the getter unimplemented, but that doesn’t seem to work.
Unfortunately in C# there’s no way around it. You need to provide a backing field for the property: