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

Time:05-25

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.

CodePudding user response:

No, you can not access to backing field in this way.

You must define backing field and validate it.

public class MyClass
{
    public MyClass(){}
    private string? _myString
    public string MyString
    {
        get
        {
            return _myString ?? throw new Exception("MyString is null");
        }
        private set => _myString  = value;
    } = null;
}

As Fred said, its better to validate it outside of property.

CodePudding user response:

Put validation in the setter and/or ensure that the constructor sets a valid/non-null default value.

Or make the property nullable to hint to the customer that they have to account for a null value possibility.

Alternatively (but less optimally for multiple reasons), make the property private and add a method for accessing it.

Strongly advise against a property get directly throwing an exception. You or the consumer will dislike the results at some point.

  • Related