If Short Notation

S

shapper

Hello,

I am using the following:

if (ValidationHelper.IsValidLenght(_Name, 0, 400)) ? _Name = value :
_errors.Add("Name", "Msg");

However is not valid. Can't I use this?

What is the correct short notation for an if with else in C#?

Thank You,
Miguel
 
S

Sebastian Hungerecker

shapper said:
if (ValidationHelper.IsValidLenght(_Name, 0, 400)) ? _Name = value :
_errors.Add("Name", "Msg");

if(ValidationHelper.IsValidLenght(_Name, 0, 400)) _Name = value;
else _errors.Add("Name", "Msg");

or:

ValidationHelper.IsValidLenght(_Name, 0, 400) ? _Name = value :
_errors.Add("Name", "Msg");

Though I don't think this is a good use case for the ternary operator (it's
not really much of a shortcut here).

HTH,
Sebastian
 
J

Jeff Johnson

I am using the following:

if (ValidationHelper.IsValidLenght(_Name, 0, 400)) ? _Name = value :
_errors.Add("Name", "Msg");

However is not valid. Can't I use this?

What is the correct short notation for an if with else in C#?

The ternary operator is meant to be just that: an operator. It is not meant
for EXECUTING two pieces of code based on a condition, it is just for
RETURNING a value.

While it is possible to do what you're trying to do using the ternary
operator (see Sebastian's reply), I doubt I'd be alone in finding the
practice to be...icky. (Look up the term "side effects," because that's
basically what you'd be relying on.)

if/else blocks don't need "short notation." They're pretty compact as-is.
 
C

Chris Dunaway

ValidationHelper.IsValidLenght(_Name, 0, 400) ? _Name = value :
_errors.Add("Name", "Msg");

Won't this throw a compiler error? don't both sides of the : in the
ternary operator have to evaluate to the same type?

Chris
 
S

Sebastian Hungerecker

Chris said:
Won't this throw a compiler error? don't both sides of the : in the
ternary operator have to evaluate to the same type?

You're right. Not only that but you also can't use the ternary operator as
as statement on its own.
Sorry about that,
Sebastian
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top