Search code examples
c#reflectionoperators

How to get defined operators for a type


I'm trying to get the list of defined operators for a specific type in order to see what kind of operations can be applied to that type.

For example, the type Guid supports operations == and !=.

So if user wants to apply <= operation for a Guid type I can handle this situation before an exception occurs.

Or if I could have the list of operators, I can force user to use only operations in the list.

The operators are seen in the object browser so there may be a way to access them via reflection but I couldn't find that way.

Any help will be appreciated.


Solution

  • 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);
                }
            }
        }
    }