Say I have the following interface:
public interface IFoo
{
public int Number { get; }
public string Text { get; }
public static int StaticNumber { get; }
public static string StaticText { get; } // Nullable warning.
}
Normally, all of these properties should work. However, if I have C#'s nullable setting enabled, then IFoo.StaticText
gives me the following warning:
Non-nullable property 'StaticText' must contain a non-null value when exiting constructor. Consider declaring the property as nullable. [ProjectName] csharp(CS8618)
Why does an interface property suddenly require an initial value to adhere to the nullable setting? Isn't that the job of the classes that implement IFoo
?
I can only seem to fix it by giving it an initial value, but when the property is meant to be an interface for some calculated value, then I end up implementing too much within the interface, and the whole point of an interface is that I shouldn't have to have any implementation details yet, right?
Here's an example of why I I don't want to set an initial value (though I'm sure there are many reasons to avoid initial values in interfaces):
using System.Collections.Generic;
public interface IDatabase<int, T>
{
public static IReadOnlyDictionary<int, T> All { get; }
public static void Init() { }
}
public class ItemDB : IDatabase<int, Item>
{
public static bool Initialized { get; private set; } = false;
static Dictionary<int, Item> _all = new();
public static IReadOnlyDictionary<int, Item> All
{
get
{
if (!Initialized) Init();
return _all;
}
}
// You'd probably initialize by pulling from a file or by making a database request.
// But for this example, Init() just adds hardcoded items.
public static void Init()
{
_all = new();
_all.Add(new Item("Item 1"));
_all.Add(new Item("Item 2"));
_all.Add(new Item("Item 3"));
_all.Add(new Item("Item 4"));
_all.Add(new Item("Item 5"));
}
}
public class Item
{
public string Name { get; private set; } = "";
public Item(string name)
{
Name = name;
}
}