Know How To Use Ternary Operators

This post is following on the series I wrote about initially here – Succinct C# Methods. This post concentrates on Ternary Operators.

Here is another example of making return values much succinct. Consider if we have a variable with a default value of null. Then, as logic is applied within the method, that value may change to something else. The result of the method is Boolean and depends on this variable’s value (that is, if the variable is null, then return false). We could write the logic block like this.

public bool SomeMethod(){
	string err = null;
	err = someMethod();

	if (err == null)
	{
		return true;
	}
	else
	{
		return false;
	}
}

Instead, we could use this.

public bool SomeMethod(){
	string err = null;
	err = someMethod();
	return err == null;
}

You have to agree that is much more efficient coding.

Til next time…


1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *