Der ternäre Operator in C♯
Es ist möglich, einen von zwei Ausdrücken, die hinter einem Fragezeichen »?« stehen und durch einen Doppelpunkt »:« getrennt sind, auszuwerten.
Ist der Wert vor dem Fragezeichen gleich [[false]], so wird der Ausdruck hinter dem Doppelpunkt (»9«) ausgewertet.
Der Wert des gesamten Ausdrucks wird dann der Wert des zuletzt ausgewerteten Ausdrucks.
Program.cs
public static class Program
{ public static void Main()
{ global::System.Console.WriteLine(false
?
8 : 9); }}
Protokoll
9
Ist der Wert vor dem Fragezeichen gleich [[true]], so wird der Ausdruck vor dem Doppelpunkt (»8«) ausgewertet.
Program.cs
public static class Program
{ public static void Main()
{ global::System.Console.WriteLine(true
?
8 : 9); }}
Protokoll
8
Übungsfragen
? Übungsfrage 0
Welche Ausgabe erzeugt das folgende Programm voraussichtlich?
Program.cs
public static class Program
{ public static void Main()
{ global::System.Console.WriteLine(false
?
1 : 2); }}
? Übungsfrage 1
Welche Ausgabe erzeugt das folgende Programm voraussichtlich?
Program.cs
public static class Program
{ public static void Main()
{ global::System.Console.WriteLine(true
?
2 : 3); }}
? Übungsfrage 2
Welche Ausgabe erzeugt das folgende Programm voraussichtlich?
Program.cs
public static class Program
{ public static void Main()
{ global::System.Console.WriteLine(true
?
"L" : "R"); }}
? Übungsfrage 3
Welche Ausgabe erzeugt das folgende Programm voraussichtlich?
Program.cs
public static class Program
{public static int f(){ global::System.Console.WriteLine( "f" ); return 0; }
public static int g(){ global::System.Console.WriteLine( "g" ); return 0; }public static void Main()
{ int c =false
?
f() : g();}}
? Übungsfrage 4
Welche Ausgabe erzeugt das folgende Programm voraussichtlich?
Program.cs
public static class Program
{public static bool f(){ global::System.Console.WriteLine( "f" ); return true; }
public static void Main()
{ int c =f()
?
4 : -6;}}
? Übungsfrage 5
Welche Ausgabe erzeugt das folgende Programm voraussichtlich?
Program.cs
public static class Program
{public static bool f(){ global::System.Console.WriteLine( "f" ); return false; }
public static void Main()
{ int c =f()
?
4 : -6;}}
? Übungsfrage 6
Welche Ausgabe erzeugt das folgende Programm voraussichtlich?
Program.cs
public static class Program
{public static void Main()
{ const bool x = 3 < 2;const int y =
x
?
7 : 5;global::System.Console.WriteLine( y ); }}
? Übungsfrage 7
Welche Ausgabe erzeugt das folgende Programm voraussichtlich?
Program.cs
public static class Program
{public static void f( int x )
{ global::System.Console.WriteLine
(x < 4
?
"q" : "p"
); }public static void Main()
{ f( 3 );
f( 4 );
f( 5 ); }}
Übungsaufgaben
/ Übungsaufgabe 0
Schreiben Sie eine Funktion, welche die Zeichenfolge »n« ausgibt, wenn sie mit »0« aufgerufen wird, und die Zeichenfolge »s« sonst.
/ Übungsaufgabe 1
Schreiben Sie eine Funktion, welche die Zeichenfolge »n« ergibt, wenn sie mit »0« aufgerufen wird, und die Zeichenfolge »s« sonst.