I expected the following lines of code to throw an exception since I am accessing the Value
property of a nullable variable that is assigned a value of null
. However, I do not get any exception when I execute the below:
int? x=null;
Console.WriteLine(x.Value==null);
But when I do:
Console.WriteLine(x.Value);
I do get an exception, as could be expected.
But what is the difference between the 2 ways of accessing x.Value
? Why do I not get an exception in the first case? Both pieces of code are after all trying to access the x.Value property.
Note: I am running the above pieces of code on the www.compileonline.com website, btw. Not sure if trying on the Visual Studio compiler would yield different results, but I do not have access to Visual Studio currently.
TIA.
Throwing an exception is as simple as using the "throw" statement. You then specify the Exception object you wish to throw. Every Exception includes a message which is a human-readable error description. It can often be related to problems with user input, server, backend, etc.
As a Python developer you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword.
*) Using swap() is an important technique for providing the strong exception guarantee, but only if swap() is non-throwing.
Any code can throw an exception: your code, code from a package written by someone else such as the packages that come with the Java platform, or the Java runtime environment. Regardless of what throws the exception, it's always thrown with the throw statement.
When using the website compile online you point out, the mono compile does a rewrite/optimalization of your code:
using System.IO;
using System;
class Program
{
static void Main()
{
int? x=null;
Console.WriteLine(x.Value==null); //-> Console.WriteLine(false);
}
}
Compiling the source code....
$mcs main.cs -out:demo.exe 2>&1
main.cs(9,38): warning CS0472: The result of comparing value type
int' with null is
false'Compilation succeeded - 1 warning(s)
Executing the program....
$mono demo.exe
False
warning CS0472 tell you that, it is a bug in the online/mono compiler they are using.
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