可過載運算子
C#允許使用者定義的型別通過使用 operator 關鍵字定義靜態成員函式來過載運算子。
以下示例說明了+運算子的實現。
如果我們有一個表示複數的 Complex 類:
public struct Complex
{
    public double Real { get; set; }
    public double Imaginary { get; set; }
}
我們想要新增選項以在此類中使用+運算子。即:
Complex a = new Complex() { Real = 1, Imaginary = 2 };
Complex b = new Complex() { Real = 4, Imaginary = 8 };
Complex c = a + b;
我們需要為該類過載+運算子。這是使用靜態函式和 operator 關鍵字完成的:
public static Complex operator +(Complex c1, Complex c2)
{
   return new Complex 
   { 
       Real = c1.Real + c2.Real,
       Imaginary = c1.Imaginary + c2.Imaginary 
   };
}
+,-,*,/等運算子都可能超載。這還包括不返回相同型別的運算子(例如,== 和 != 可以過載,儘管返回布林值)下面的規則也在這裡強制執行。
比較運算子必須成對過載(例如,如果 < 過載,則 > 也需要過載)。
在 MSDN 上可以看到可過載運算子的完整列表(以及不可過載運算子和對某些可過載運算子的限制) - 可過載運算子(C#程式設計指南) 。
Version >= 7
使用 C#7.0 的模式匹配機制引入了 operator is 的過載。有關詳細資訊,請參閱模式匹配
給定型別 Cartesian 定義如下
public class Cartesian
{
    public int X { get; }
    public int Y { get; }
}   
例如,可以為 Polar 座標定義可過載的 operator is
public static class Polar
{
    public static bool operator is(Cartesian c, out double R, out double Theta)
    {
        R = Math.Sqrt(c.X*c.X + c.Y*c.Y);
        Theta = Math.Atan2(c.Y, c.X);
        return c.X != 0 || c.Y != 0;
    }
}
可以像這樣使用
var c = Cartesian(3, 4);
if (c is Polar(var R, *))
{
    Console.WriteLine(R);
}
(該示例取自 Roslyn 模式匹配文件 )