Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse ?? operator

Tags:

c#

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

like image 748
Egor Pavlikhin Avatar asked Apr 13 '10 05:04

Egor Pavlikhin


5 Answers

You're trying to be too clever... Just use an if:

if(logged != null) logger.Log(message);
like image 95
Lance McNearney Avatar answered Oct 16 '22 18:10

Lance McNearney


No. The closest you can come is probably via a null object design:

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

where NullLogger.Instance is a Logger that just no-ops all its methods. (Of course, if you require the default behaviour to do something rather than no-op-ing, you can substitute a suitable Logger.Default or whatever instead of the NullLogger.Instance.)

like image 23
itowlson Avatar answered Oct 16 '22 19:10

itowlson


:)

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

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

UPD [31.07.2020]:

Since C# 6, you can do it with null-conditional operator like this:

logger?.Log(message);

MSDN:

Available in C# 6 and later, a null-conditional operator applies a member access, ?., or element access, ?[], operation to its operand only if that operand evaluates to non-null; otherwise, it returns null.

like image 34
Arnis Lapsa Avatar answered Oct 16 '22 18:10

Arnis Lapsa


Or, if you like surprising your co-workers, you could use an extension method:

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

and just do

logger = null;
logger.Log("Hello world, not.");
like image 45
Wikser Avatar answered Oct 16 '22 18:10

Wikser


I was looking for a reverse ?? operator too, so I bumped onto this old question that can be answered today thanks to the null conditional operator, which was introduced in C# 6:

logger?.Log(message);

This will call the Log method only if logger is not null :)

like image 26
Larry Avatar answered Oct 16 '22 18:10

Larry