views:

77

answers:

1

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.


alt text

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.

Thanks..

+6  A: 

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())
        {
            if (method.IsSpecialName)
            {
                Console.WriteLine(method.Name);
            }
        }
    }
}
Jon Skeet
hi, thanks for the quick reply!i think that works for most of the types but when i try Int32 it returns an empty set.any suggestion?
Cankut
Yes, operators on primitive types are "funny" like that. I suspect you'd have to hard-code a list of them, basically. Don't forget that primitives don't include `decimal`, `DateTime`, `TimeSpan or `Guid`.
Jon Skeet
thanks very much :)
Cankut
Just for completeness, the "lifted" operators on `Nullable<T>` would also qualify as "funny" ;-p
Marc Gravell