Skip to content

Instantly share code, notes, and snippets.

@Nasicus
Last active September 7, 2015 07:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Nasicus/893da00ae8d862bde315 to your computer and use it in GitHub Desktop.
Save Nasicus/893da00ae8d862bde315 to your computer and use it in GitHub Desktop.
Null conditional operator: Check value for true (boolean check)

I just want to know what you guys think of the following code part and if you think it's readable or if you'd do it differentely.

Let's assume we have this class:

public class Foo
{
  public bool IsFooBar { get; set; }
}

An now we want to check for IsFooBar, but are not sure if our instance of Foo is null:

internal class Program
{
	private static void Main(string[] args)
	{
		Foo foo = GetFoo();
		bool secondCondition = GetSecondCondition();
		if ((foo?.IsFooBar ?? false) && secondCondition) //relevant line
		{
			//true
		}
	}

	private static Foo GetFoo()
	{
		//clever logic is here, CAN return null
		return null;
	}

	private static bool GetSecondCondition()
	{
		//even mor clever logic
		return true;
	}
}

What do think about the relevant line? Is this code nice? Or would you rather write:

	if (foo != null && foo.IsFooBar && secondCondition)

Or maybe you guys even got a better idea.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment