Skip to content

Instantly share code, notes, and snippets.

@zs40x
Last active April 10, 2016 07:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zs40x/1f58484e12199ccf41c245b07244c03d to your computer and use it in GitHub Desktop.
Save zs40x/1f58484e12199ccf41c245b07244c03d to your computer and use it in GitHub Desktop.
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