If Short Notation

  • Thread starter Thread starter shapper
  • Start date Start date
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
 
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
 
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.
 
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
 
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
 
Back
Top