How to get defined operators for a type in .net

Get the methods with Type.GetMethods, then use MethodInfo.IsSpecialName to discover operators, conversions etc. Here’s an example:

using System;
using System.Reflection;

public class Foo
{
    public static Foo operator +(Foo x, Foo y)
    {
        return new Foo();
    }
    
    public static implicit operator string(Foo x)
    {
        return "";
    }
}

public class Example 
{
    
    public static void Main()
    {
        foreach (MethodInfo method in typeof(Foo).GetMethods(BindingFlags.Static | BindingFlags.Public))
        {
            if (method.IsSpecialName && method.Name.StartsWith("op_"))
            {
                Console.WriteLine(method.Name);
            }
        }
    }
}

Leave a Comment