Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullable getter, but non nullable setter

Tags:

c#

.net

.net-core

Using c# version 8.0 introduction of nullable reference types and non-nullable reference types, I can do something like this:

public class Response
{
    public Response(Exception? ex)
    {
        _ex = ex;
    }

    private Exception? _ex;

    public Exception? Ex
    {
        get => _ex;
        set { _ex = value; }
    }
}

I can initialize _ex to null via the constructor. However, once the instance is created I would like the setter to be unable to set Ex value to null (by removing the question mark from the type)... something like the code below, which of course, does not compile.

public class Response
{
    public Response(Exception? ex)
    {
        _ex = ex;
    }

    private Exception? _ex;

    public Exception? Ex
    {
        get => _ex;
    }

    public Exception Ex
    {
        set { _ex = value; }
    }
}

One work around of course is to set the _ex value with a method, instead of a setter, but I figured to ask anyway.

like image 461
Urielzen Avatar asked Oct 23 '25 04:10

Urielzen


1 Answers

That is the purpose of the [DisallowNull] attribute, which "specifies that null is disallowed as an input even if the corresponding type allows it".

Leave the property nullable so that any callers accessing the getter will be properly informed that its value may be null, but attempts to explicitly set it to null will generate the expected warning.

The attribute is added to the property, not the setter:

[DisallowNull]
public Exception? Ex
{
    get => _ex;
    set => _ex = value;
}

More info: https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.codeanalysis.disallownullattribute

There are several other such attributes which are intended to be used with nullable reference type compiler checks: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/attributes/nullable-analysis

(Also note that you can use => expression syntax for the set as well.)

like image 99
Tobias J Avatar answered Oct 25 '25 16:10

Tobias J



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!