Change this condition so that it doesn't always evaluate to 'true' - C#

Hi Everyone, Good Day.
I have a piece of code like this which will append the url depending on the bool value passes to the function.

public static string function ( string url, bool val)
{
	if(val)
	{
		String urlbuild = new StringBuilder();
		urlbuild.Append(url);
		urbuild.Append("sometext");
		String newurl = urlbuild.ToString();
		return newurl;
	}
	else if(!val)
	{
		String urlbuild = new StringBuilder();
		urlbuild.Append(url);
		urbuild.Append("someOthertext");
		String newurl = urlbuild.ToString();
		return newurl;
	}
	else
		return url;
}

So in Else if part , I am getting a Sonarqube bug "Change this condition so that it does not always evaluate to ‘true’ ; eome subsequent code is never executed. Can someone help or guide me on this?

Hi,

Welcome to the community!

Let’s boil your code down:

if(val) 
{
  // stuff
  // return newurl
}
else if (!val)
{
  // slightly different stuff
  // return newurl
}
else
  // default
  // return url

You’ve provided three paths, but you’re basing the path choice on a boolean test. Boolean tests only have two outcomes: true and false. There is no third value. So you’re never going to get to the else. That means you can streamline your code to:

if(val) 
{
  // stuff
  // return newurl
}
else if (!val)
{
  // slightly different stuff
  // return newurl
}

But that’s not all. Again, you’re doing a boolean test and boolean tests only have two outcomes. Your if tests for (val). If that condition is true, control flow moves into that block. If you don’t move into that block (and exit the method with your return statement) then you automatically know that !val is true. There’s no reason to re-test it.

So the code further streamlines to:

if(val) 
{
  // stuff
  // return newurl
}
else
{
  // slightly different stuff
  // return newurl
}

Or, since control flow exits the method once you enter the if block, just:

if(val) 
{
  // stuff
  // return newurl
}
// slightly different stuff
// return newurl

 
HTH,
ann