I realize the proper way to handle nullable types is to use the HasValue property. But I would like to know why the following switch statement breaks on the null case instead of default. Using VS2015 C#4.0. Another computer that is using VS2010 C#4.0 does not have this same problem.
private void Testing()
{
bool? boolValue = true;
switch (boolValue)
{
case null:
break; //even though value is true, code runs here
default:
break;
}
}
Edit: Behavior is observed with any Nullable
if only case Null
and default
is specified.
C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...
In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.
What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.
C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.
This is going to be a very short answer: You just hit Roslyn bug #4701, reported two weeks ago.
The milestone is set to 1.1, so right now you'll have to workaround this with a separate if
clause, while waiting for the next compiler update.
This is not an answer, I am just sharing IL code generated by VS2013 and VS2015.
Original C# code:
public void Testing()
{
bool? boolValue = true;
switch (boolValue)
{
case null:
Console.WriteLine("null");
break;
default:
Console.WriteLine("default");
break;
}
}
VS2013 IL (decompiled):
public void Testing()
{
bool? boolValue = new bool?(true);
bool valueOrDefault = boolValue.GetValueOrDefault();
if (boolValue.HasValue)
{
Console.WriteLine("default");
}
else
{
Console.WriteLine("null");
}
}
VS2015 IL (decompiled):
public void Testing()
{
bool? flag = new bool?(true);
bool? flag2 = flag;
bool? flag3 = flag2;
if (flag3.HasValue)
{
bool valueOrDefault = flag3.GetValueOrDefault();
}
Console.WriteLine("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