The operator '?' cannot be applied to an operand of type "method group"

This is a question about the recently introduced C # null check statement.

Assuming I have an interface, for example:

interface ILogger
{
    void Log(string message);
}

and a function that expects registration actions:

void DoWork(Action<string> logAction)
{
    // Do work and use @logAction
}

Why can I get the following compiler error if I try to write:

void Main(string[] args)
{
    ILogger logger = GetLogger(); // Assume GetLogger() may return null

    //
    // Compiler error: 
    // Operator '?' cannot be applied to operand of type 'method group'
    //
    DoWork(logger?.Log);   
}
+4
source share
3 answers

There is nothing special in ?., it works the same as with ?:: it logger?.Logwill give the same result as logger == null ? null : logger.Log, except that it loggeris evaluated only once.

, logger == null ? null : logger.Log #. ?: , , null, logger.Log . , . logger == null ? null : (Action<string>) logger.Log.

, , # 6, , ?.: logger?.Log , logger.Log , logger?.Log , , , # .

+13

interface ILogger
{
    //void Log(string message);
    Action<string> Log {get; }
}

logger?.Log.

ILogger :

class Logger : ILogger
{
    Action<string> Log => str => { /* Do stuff with str */ };
}
0

@hvd

Null Conditional Operator (?.) Null-Coalescing (??)  

string userName = null;
int len = userName.Length;

userName.Length

: " " System.NullReferenceException " ConsoleApplication...   : ​​ . "

string userName = null;
int? len = userName.Length;

int? len = userName?.Length;

null

. , int? (Nullable int), , , , 0.

, (?.) (??)

int len = userName?.Length ?? 0;

.

, ,

myCustomEventHandler?.Invoke(, EventArgs.Empty);

where "myCustomEventHandler" is a public event prior to C # 6.0, we must create a local copy of "myCustomEventHandler", otherwise this may throw an exception if muti-threaded is used. whereas in C # 6 we can directly call "myCustomEventHandler" without creating a local copy, and this is thread safe.

eg. in c # 5

var handler= this.myCustomEventHandler;
if (handler!= null)
    handler(…)

in c # 6

myCustomEventHandler?.Invoke(e)
-1
source

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


All Articles