Search code examples
c#propertiescilaccessormutators

Overriding shorthand properties in C#


My understanding is that when I create a shorthand property in c#, this translates to a field created for it once It's compiled.

class Hello {
  public bool Hi { set ; get ; }
}

My question is what happens if the shorthand property is virtual and then overridden:

class Hello {
  virtual public bool Hi { set ; get ; }
}

//The class and the property can't have the same name
//class Hi : Hello {
class Bonjour : Hello {
  override public bool Hi {
    set { }
    get { return true ; }
  }
}

I have overridden the virtual property entirely. Will this still generate a field when compiling the class Hi that I will not be able to access anymore?

Thank you.


Solution

  • Yes, the field will still be generated, as your Hello class still needs to be usable on its own.

    If you want to access the underlying field from the Bonjour class, you can refer to the base property through base.Hi.

    If you never intended for the Hello class to be usable on its own in the first place, make the class and the property abstract. No field will be generated then.

    Here's an example of what happens when you compile and then decompile both cases.