Skip to content

Instantly share code, notes, and snippets.

@punmechanic
Forked from Nasicus/NullConditionalOperator.md
Created September 4, 2015 13:18
Show Gist options
  • Save punmechanic/dae3e97730e668993a1d to your computer and use it in GitHub Desktop.
Save punmechanic/dae3e97730e668993a1d 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