Search code examples
c#.netvisual-studio.net-core

C# How to overcome Interface Nullability for getters


Given:

//Common interface for objects that may have an Id value
interface IMaybeHasId
{
    int? Id { get; }  //Note this is a GET only
}

//Object A never has an Id, this code works fine
class ObjectA : IMaybeHasId
{
    public int? Id => null;
}

//Object B always has an Id
//This code will not work as Id here is Int not Int?
class ObjectB : IMaybeHasId
{
    public int Id => 10;
}

I need this because when my code works with a pure reference to Object B The code can expect that Id is always available.

When working with a pure reference to Object A, the Id may not be available.

But I want to place them into a common collection ie List()

When working with the items in the list its ok to worry about Id possible being null as per the interface. Ie we would have an object reference via the interface contract where Id is Int? Totally fine.

The compiler will stop the above code from compiling

This is a real pain as from a human perspective there is no real issue here. The contract of Object B (Always having an Id) would comply with the interface that the object type May have an Id. Note this contract is a GET so having a non null value fits into a nullable restriction. It just happens to never be null.

Obviously this would not be work if the property was writable / setter. Because object B would not be able to accept null values. But in this case we are readonly so it 'could' work.

If anyone has a nice way to solve this issue then please let me know.


Solution

  • You need to implement the interface explicitly. Then you can easily keep the public int Id => 10; yet still implement the interface.

    class ObjectB : IMaybeHasId
    {
        public int Id => 10;
        int? IMaybeHasId.Id => this.Id;
    }