Search code examples
c#stringnon-nullable

C# creating a non-nullable string. Is it possible? Somehow?


So you can't inherit string. You can't make a non-nullable string. But I want to do this. I want a class, let's call it nString that returns a default value when it would otherwise be null. I have JSON objects that might have who knows how many null strings, or even null objects. I want to create structs that have strings that will never return null.

public struct Struct
{
    public nString value;
    public nString value2;
}

I suppose I could do something like this:

public struct Struct
{
    public string val { get { return val ?? "N/A"; } set { val = value; } }
    public string val2 { get { return val2 ?? "N/A"; } set { val2 = value; } };
}

But that's so much more work. Is there any way to do this?


Solution

  • You could of course have the following nString struct:

    public struct nString
    {
        public nString(string value)
            : this()
        {
            Value = value ?? "N/A";
        }
    
        public string Value
        {
            get;
            private set;
        }
    
        public static implicit operator nString(string value)
        {
            return new nString(value);
        }
    
        public static implicit operator string(nString value)
        {
            return value.Value;
        }
    }
    
    ...
    
    public nString val 
    { 
        get;
        set;
    }
    
    obj.val = null;
    string x = obj.val; // <-- x will become "N/A";
    

    This would allow casting from and to string. Under the hood it performs the same cast as your example, you just don't have to type it out for every property. I do wonder what this does to maintainability for your application though.