What does the question mark in member access mean

2019-01-08 01:42发布

Can someone please explain to me what does the question mark in the member access in the following code means?

Is it part of standard C#? I get parse errors when trying to compile this file in Xamarin Studio.

this.AnalyzerLoadFailed?.Invoke(this, new AnalyzerLoadFailureEventArgs(AnalyzerLoadFailureEventArgs.FailureErrorCode.NoAnalyzers, null, null));

AnalyzerFileReference.cs line 195

2条回答
疯言疯语
2楼-- · 2019-01-08 02:26

In C# version 6 it will be shorthand for

if (this.AnalyzerLoadFailed != null)
    this.AnalyzerLoadFailed.Invoke(this, new AnalyzerLoadFailureEventArgs(AnalyzerLoadFailureEventArgs.FailureErrorCode.NoAnalyzers, null, null));
查看更多
We Are One
3楼-- · 2019-01-08 02:32

It is Null Propagation operator introduced in C# 6, it will call the method only if object this.AnalyzerLoadFailed is not null:

this.AnalyzerLoadFailed?.Invoke(this, new AnalyzerLoadFailureEventArgs(AnalyzerLoadFailureEventArgs.FailureErrorCode.NoAnalyzers, null, null));

is equal to :

if( this.AnalyzerLoadFailed != null)
    this.AnalyzerLoadFailed.Invoke(this, new AnalyzerLoadFailureEventArgs(AnalyzerLoadFailureEventArgs.FailureErrorCode.NoAnalyzers, null, null));

See C# 6.0 – Null Propagation Operator , also you can see here

i also once wrote about this upcoming feature in c# 6 here

查看更多
登录 后发表回答