Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused with the ? operator in C#

Tags:

c#

I have a variable called full_name if the full_name has a string length > 5 I would like to set nm to the first 4 characters of full_name otherwise I would like to set nm to all the characters of full_name.

var nm;

if (full_name.Length > 5)
{
    nm = full_name.Substring(0, 4);
}
else
{
    nm = full_name;
};

I'm totally confused with the "?" operator.

Could I use it for this ?

like image 928
JudyJ Avatar asked May 21 '11 13:05

JudyJ


1 Answers

var nm = full_name.Length > 5 ? full_name.Substring(0, 4) : full_name;
like image 128
Marc Gravell Avatar answered Sep 23 '22 01:09

Marc Gravell