0

I am looking to identify auto-implemented properties on a class that have a getter, as compared to other properties' getters which use some other state to determine their values.

For example, take the follow class:

public class RgbColor {

    public int Red { get; }
    public int Green { get; }
    public int Blue { get; }

    public string Hex => String.Format("#{0:X2}{1:X2}{2:X2}", this.Red, this.Green, this.Blue);
    public bool IsBlack { get { return this.Red == 0 && this.Green == 0 && this.Blue == 0; } }
    public bool IsWhite { get { return this.isWhite; } }

    private bool isWhite;

    public RgbColor(int red, int green, int blue) {
        this.Red = red;
        this.Green = green;
        this.Blue = blue;

        this.isWhite = (this.Red == 255 && this.Green == 255 && this.Blue == 255);
    }
}

Is there a way to detect that, in the above example, the getters for Red, Green and Blue are defined using auto-implemented properties, and the getters for Hex, IsWhite, and IsBlack are not?

Technetium
  • 5,902
  • 2
  • 43
  • 54

1 Answers1

0

Use reflection:

public static bool IsAutoProperty(this PropertyInfo prop)
{
    return prop.DeclaringType.GetFields(BindingFlags.NonPublic |BindingFlags.Instance).
           Any(p => p.Name.Contains("<" + prop.Name + ">"));
}
David
  • 15,894
  • 22
  • 55
  • 66