Aditya Korti
Aditya Korti

Reputation: 672

How do I to shorten If else

My code looks like

private bool IsUserAditya(string username)
{
  return username == "Aditya"? true : false;
}

Can I shorten it further?

I would appreciate any help on this.

Upvotes: 4

Views: 158

Answers (4)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149518

Not directly related to shortening (properly even longer), but if you're comparing an input from a user, such as a username, use string.Equals which takes a StringComparison object:

private bool IsUserAditya(string username)
{
    return username.Equals("Aditya", StringComparison.OrdinalIgnoreCase);
}

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460028

Can I shorten it further?

Yes, a little bit

return username == "Aditya";

Any comparison in C# returns a bool, so no need to use the conditional operator.

Upvotes: 6

Amit
Amit

Reputation: 46323

Even shorter...

private bool IsUserAditya(string u){return u=="Aditya";}

but that only "shortens" the source code. Generated binary will be same size.

Upvotes: 0

M. Nasir Javaid
M. Nasir Javaid

Reputation: 5990

private bool IsUserAditya(string username)
{
    return username == "Aditya";
}

Upvotes: 3

Related Questions