Search code examples
c#getter-settersyntactic-sugarautomatic-propertiesbacking-field

Can I define a custom getter for a C# auto-implemented property (a.k.a. auto backing field)?


Note: I know how to accomplish this without using auto-implemented properties, but I'm wondering if C# has a built-in way to do this.

Let's say I have this simple example of an auto-implemented property (a.k.a. auto backing field):

public class MyClass
{
    public MyClass(){}
    public string MyString { get; private set; }
}

Now, I would like to return a custom exception in the getter if the auto backing field is null:

public class MyClass
{
    public MyClass(){}
    public string MyString
    {
        get
        {
            return [backing field] ?? throw new Exception("MyString is null");
        }
        private set;
    } = null;
}

Do newer C# versions support something like this? Perhaps there is some syntactic sugar that I can use in place of [backing field] to access the backing field that is automatically created by the compiler?

Note on putting an exception in the getter: I know it shouldn't be a habit. But Microsoft does it occasionally; for example, the property HttpContext.Request.Form will throw an exception if the request is not of the proper content-type.


Solution

  • Update 2024-04-25 by user3163495: The feature is planned to be in C# 13 / .NET 9.

    Link: https://github.com/dotnet/csharplang/issues/140#issuecomment-1940720831


    Original answer:

    I'm surprised noone mentioned the field keyword, it is exactly what you are asking for (what you would use instead of [backing field] in your example). It was supposed to be shipped with C# 10. It seems it is going to be shipped with C# 11 instead (?)

    Search for Field Keyword here.