Elitmiar
Elitmiar

Reputation: 36839

What does the following statement do?

I'm not a c# programmer at all, but need to get certain calculations from a C# app. No I ran into something that I'm not sure if what the output is

I have the following line of code

pageSizeFactor = PrintingRequirements.FormSize == FormSize.A4 ? 1 : 2;

I just need to confirm if I am correct, the above means the following, pageSizeFactor = the Formsize, so if the Formsize is A4 pageSizeFactor will be 1 else it will be 2?

Upvotes: 1

Views: 1819

Answers (3)

icktoofay
icktoofay

Reputation: 128991

Yes; if PrintingRequirements.FormSize is FormSize.A4, pageSizeFactor will be 1. Otherwise, it will be 2.

That operator (?:) is known as the conditional operator. It is also sometimes known as the ternary operator. Its syntax goes like this:

a ? b : c

If a evaluates to true, the result will be b; otherwise, it will be c.

Upvotes: 6

Nasreddine
Nasreddine

Reputation: 37798

A simple way to write the code you provided is:

if (PrintingRequirements.FormSize == FormSize.A4){
    pageSizeFactor =  1;
} else {
    pageSizeFactor =  2;
}

Upvotes: 1

Richard
Richard

Reputation: 108975

That is the conditional operator:

result = boolean-expression ? expression-if-true : expression-if-false

Essentially if - else inline.

Upvotes: 5

Related Questions