Reverse?? operator

Is it possible to do something like this in C #?

logger != null ? logger.Log(message) : ; // do nothing if null

or

logger !?? logger.Log(message); // do only if not null

+4
source share
5 answers

:)

if (logger!=null) logger.Log(message);

No ... unfortunately, such an operator does not exist.

+5
source

No. The closest you can find is probably related to the null design of the object:

(logger ?? NullLogger.Instance).Log(message);

where NullLogger.Instance is a Logger that just does not handle all of its methods. (Of course, if you want the default behavior to do something, not no-op-ing, you can replace the appropriate Logger.Default or something else instead of NullLogger.Instance.)

+7
source

... if:

if(logged != null) logger.Log(message);
+6

, , :

public static void Log(this Logger logger, string message)
{
    if(logger != null)
        logger.ReallyLog(message);
}

logger = null;
logger.Log("Hello world, not.");
+3

I was looking for a reverse ?? also an operator, so I came across this old question that can be answered today thanks to the zero conditional operator , which was introduced in C # 6:

logger?.Log(message);

This will Logonly call the method if loggerit is not equal to zero :)

+1
source

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


All Articles