using System;
public class A{
public bool func(){
return true;
}
public int func2(){
return 10;
}
}
public class HelloWorld
{
public static void Main(string[] args)
{
A a = new A();
if(a?.func()){
Console.WriteLine("true"); // Error
}
if(a?.func2() == 10){
Console.WriteLine("true"); // print: True
}
}
}
Like above case, I want to use null conditional operator with A function that returns a bool value. But, It throws error only when used with bool returning function.
Can I know why it works like that?
Ironically, It works well with the phrase
if(a?.func() == true){
Console.WriteLine("true"); // print: true
}
Please, note that even if
func
returnsbool
returns nullable
bool?
(true
,false
and ...null
):So you can put
here .net compares
T?
andT
instances (T
isbool
in our case). It does it as followAnother way is to use
??
to mapnull
intotrue
orfalse
The very same logic with
here
a?.func2()
returns nullableint?
which you compare as== 10
, i.e.