Search code examples
c#.netnull-coalescing-operatornull-coalescing

Is there a way to implement and make use of a "NOT null coalescing" operator?


Is there a not null coalescing operator in C# which in case could be used such as:

public void Foo(string arg1)
{
    Bar b = arg1 !?? Bar.Parse(arg1);   
}

The following case made me think of it:

public void SomeMethod(string strStartDate)
{
    DateTime? dtStartDate = strStartDate !?? DateTime.ParseExact(strStartDate, "dd.MM.yyyy", System.Globalization.CultureInfo.InvariantCulture);
}

I might not have strStartDate information, which in case will be null but if i do; i'm always certain that it will be in expected format. So instead of initializing dtStartDate = null and trying to parse and set the value within try catch block. It seems to be more useful.

I suppose the answer is no (and there is no such operator !?? or anything else) I wonder if there's a way to implement this logic, would it be worth and what would be the cases that it comes useful.


Solution

  • Mads Torgersen has publicly said that a null-propagating operator is under consideration for the next version of C# (but also emphasised that this doesn't mean it will be there). This would allow code like:

    var value = someValue?.Method()?.AnotherMethod();
    

    where the ?. returns null if the operand (on the left) is null, else will evaluate the right hand side. I suspect that would get you a lot of the way here, especially if combined with (say) extension methods; for example:

    DateTime? dtStartDate = strStartDate?.MyParse();
    

    where:

    static DateTime MyParse(this string value) {
        return DateTime.ParseExact(value, "dd.MM.yyyy",
             System.Globalization.CultureInfo.InvariantCulture
    );
    

    However! You could do the same thing right now just using extension methods:

    DateTime? dtStartDate = strStartDate.MyParse();
    
    static DateTime? MyParse(this string value) {
        if(value == null) return null;
        return DateTime.ParseExact(value, "dd.MM.yyyy",
             System.Globalization.CultureInfo.InvariantCulture
    );