+ 2
How the '?' And ':' Operator works in C#?
i have been seeing these several times without knowing what is it. maybe i missed something in the lesson... is it an operator? still need your help! what does it do, when do you use it best, and maybe an example if possible please...
6 odpowiedzi
+ 2
Yeah, its really nice for return values. Look at this recursive factorial example:
int Factorial(int n)
{
return ((n == 1) ? 1 : n * Factorial(n - 1));
}
+ 1
Your welcome :)
0
The : operator is used in inheritance:
public class Dog : Animal
{
public Dog() : base()
{}
}
The ? operator is used when you want to allow a variable to be able to take null as a value:
int? a = null;
double? b = null;
etc...
Both operators are also used in conditional expressions:
int x = (0 > 1) ? 4 : 5;
If the condition within the brackets is true the value of x will be 4 (the value before the : operator) else it will be 5 (the value after the : operator). In this case it will be 5
0
ooh. its like an if else but in short
0
i understand now. thank you
0
Unnecessary extra information: This operator is known as the "ternary conditional operator", or usually just the "ternary operator" since there aren't any other ternary operators (in C#, that is. This may be false, someone please correct me if I'm wrong).