+ 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...

19th Apr 2017, 3:07 PM
AryaZaky Iman Fauzy
AryaZaky Iman Fauzy - avatar
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)); }
19th Apr 2017, 3:28 PM
G4S
+ 1
Your welcome :)
19th Apr 2017, 4:12 PM
G4S
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
19th Apr 2017, 3:22 PM
G4S
0
ooh. its like an if else but in short
19th Apr 2017, 3:24 PM
AryaZaky Iman Fauzy
AryaZaky Iman Fauzy - avatar
0
i understand now. thank you
19th Apr 2017, 3:32 PM
AryaZaky Iman Fauzy
AryaZaky Iman Fauzy - avatar
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).
26th Apr 2017, 12:04 AM
Omar
Omar - avatar