Last active
April 10, 2016 07:36
-
-
Save zs40x/1f58484e12199ccf41c245b07244c03d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Engine | |
{ | |
public bool IsRunning { get; private set; } | |
public void Start() { } | |
public void Stop() { } | |
} | |
class Machine | |
{ | |
public Engine Engine { get; } | |
} | |
public class Program | |
{ | |
static void Main() | |
{ | |
Machine notInitializedMachine = null; | |
// the problem | |
try { | |
notInitializedMachine.Engine.Start(); | |
} catch( NullReferenceException ) { | |
Console.WriteLine("this ends in an NullReferenceException...."); | |
} | |
// nothing happens - the machine instance is initialized, | |
// but the engine property is null --> no exception! | |
notInitializedMachine = new Machine(); | |
notInitializedMachine?.Engine?.Start(); | |
/* | |
let's assume we just want to know if the engine is running. | |
In case the machine doesn't have an engine (yet), it should | |
simply be false. | |
this will not work, because IsRunning is bool? in this context: | |
bool IsEngineRunning = notInitializedMachine?.Engine?.IsRunning; | |
-> okay - null coalescing operator to the rescue | |
*/ | |
bool IsEngineRunning = notInitializedMachine?.Engine?.IsRunning ?? false; | |
Console.WriteLine($"{nameof(IsEngineRunning)}: {IsEngineRunning}"); | |
// --> IsEngineRunning: False | |
/* | |
without the null conditional & coalescing operators it may look like this: | |
*/ | |
IsEngineRunning = false; | |
if(notInitializedMachine != null) | |
{ | |
if(notInitializedMachine.Engine != null) | |
{ | |
IsEngineRunning = notInitializedMachine.Engine.IsRunning; | |
} | |
} | |
Console.WriteLine($"{nameof(IsEngineRunning)}: {IsEngineRunning}"); | |
// --> IsEngineRunning: False | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment