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
You're trying to be too clever... Just use an if
:
if(logged != null) logger.Log(message);
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.)
:)
if (logger!=null) logger.Log(message);
No... unfortunately such an operator does not exist.
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.
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.");
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With