简体   繁体   中英

How can I declare a new operator “!??” (test object is not null)

Is there a way to declare a unary operator such as '!??'

I imagine something like this (non working code)

public bool operator !??<T> (this <T> item) {
    return item != null;
}

so I would use it like such

// day is a value and might possibly be null
string greeting = name !?? "hello there " + name;

I find myself often having to do this awkwardness

// day is a value and might be null
string greeting = day != null ? "hello there " + name : "";

It's fairly clear in the example I've provided, but when you are using getter/setters for view-models, it gets a bit confusing to stare at, and raises the chance of a logical error being missed. As such:

public DateTime? SearchDate {
    get { return _searchDate; }
    set { _searchDate = value != null ? value.Value : value; }
}

This is completely impossible.

Instead, you can use C# 6's ?. operator:

value?.Value

As has been said, you cannot declare new operators in C#, ever, at all. This is a limitation of the language, the compiler, and the environment.

What you CAN do is utilize the null coalescing operator or write a few generic Extension Methods to handle what you want, such as

public static string EmptyIfNull(this string source, string ifValue, string ifNull = "")
{
    return source != null ? ifValue : ifNull;
}

and implemented via

string greeting = name.EmptyIfNull("hello there " + name);

C#不允许您定义全新的运算符,您只能重载一组特定的现有运算符

根本无法在C#中声明新运算符,您只能覆盖现有运算符。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM