Csharp/CSharp Tutorial/Operator/Ternary Operator

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Prevent a division by zero using the ? operator

using System; 
 
class Example { 
  public static void Main() { 
    int result; 
 
    for(int i = -5; i < 6; i++) { 
      result = i != 0 ? 100 / i : 0; 
      if(i != 0)  
        Console.WriteLine("100 / " + i + " is " + result); 
    } 
  } 
}
100 / -5 is -20
100 / -4 is -25
100 / -3 is -33
100 / -2 is -50
100 / -1 is -100
100 / 1 is 100
100 / 2 is 50
100 / 3 is 33
100 / 4 is 25
100 / 5 is 20

Simplest Data type cast operator

using System;
class MyDataType
{
   public static explicit operator int(MyDataType li)   // Convert type
   {
      Console.WriteLine("explicit operator int");
      return 0;
   }
   public static explicit operator MyDataType(int x)    // Convert type
   {
      Console.WriteLine("public static explicit operator MyDataType");
      return new MyDataType();
   }
}
class MainClass
{
   static void Main()
   {
      MyDataType d = (MyDataType)5;
      int Five = (int)d;
      Console.WriteLine(Five);
   }
}
public static explicit operator MyDataType
explicit operator int
0

The ? Operator

  1. The ? operator is often used to replace certain types of if-then-else constructions.
  2. The ? is called a ternary operator because it requires three operands.

It takes the general form


Exp1 ? Exp2 : Exp3;
  1. where Exp1 is a bool expression, and Exp2 and Exp3 are expressions.
  2. The type of Exp2 and Exp3 must be the same.

The value of a ? expression is determined like this:

  1. Exp1 is evaluated.
  2. If it is true, then Exp2 is evaluated and becomes the value of the entire ? expression.
  3. If Exp1 is false, then Exp3 is evaluated, and its value becomes the value of the expression.

The ternary operator

class MainClass
{
  public static void Main()
  {
    int result;
    result = 10 > 1 ? 20 : 10;
    System.Console.WriteLine("result = " + result);
    result = 10 < 1 ? 20 : 10;
    System.Console.WriteLine("result = " + result);
  }
}
result = 20
result = 10

Use ternary operator in Console.WriteLine function

using System;
class MainClass
{
   static void Main()
   {
      int x = 10, y = 9;
      Console.WriteLine("x is{0} greater than y",
                            x > y          // Condition
                            ? ""           // Expression 1
                            : " not");     // Expression 2
      y = 11;
      Console.WriteLine("x is{0} greater than y",
                            x > y          // Condition
                            ? ""           // Expression 1
                            : " not");     // Expression 2
   }
}
x is greater than y
x is not greater than y