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

Is there a non- zero coalescing operator in C#, which in this case can be used, for example:

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

In the following case, I thought about this:

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

I may not have information strStartDate, which in case will be null, but if I do it; I am always sure that it will be in the expected format. Therefore, instead of initializing dtStartDate = nulland trying parse, set the value in the block try catch. This seems more useful.

I believe the answer is no (and there is no such operator !??or anything else) I wonder if there is a way to implement this logic, whether it will cost and what will be the cases when it comes in handy.

+4
2

Mads Torgersen , , , # ( , , ). , :

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

?. null, () null, . , , () ; :

DateTime? dtStartDate = strStartDate?.MyParse();

:

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

! , :

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
);
+6

?::

DateTime? dtStartDate = strStartDate == null ? null : DateTime.ParseExact(…)

, :

DateTime? a = (string)b !?? (DateTime)c;

, , b null, (null) string a.

+2

Source: https://habr.com/ru/post/1524236/


All Articles