32

In my small project I'm using System.Reflection classes to produce executable code. I need to call the + operator of a custom type. Does anybody know how can I call customized operator of custom class using C# reflection?

Mohammad Dehghan
  • 17,853
  • 3
  • 55
  • 72
user35443
  • 6,309
  • 12
  • 52
  • 75

3 Answers3

47

C# compiler converts overloaded operator to functions with name op_XXXX where XXXX is the operation. For example, operator + is compiled as op_Addition.

Here is the full list of overloadable operators and their respective method names:

┌──────────────────────────┬───────────────────────┬──────────────────────────┐
│         Operator         │      Method Name      │       Description        │
├──────────────────────────┼───────────────────────┼──────────────────────────┤
│ operator +               │ op_UnaryPlus          │ Unary                    │
│ operator -               │ op_UnaryNegation      │ Unary                    │
│ operator ++              │ op_Increment          │ Unary                    │
│ operator --              │ op_Decrement          │ Unary                    │
│ operator !               │ op_LogicalNot         │ Unary                    │
│ operator +               │ op_Addition           │                          │
│ operator -               │ op_Subtraction        │                          │
│ operator *               │ op_Multiply           │                          │
│ operator /               │ op_Division           │                          │
│ operator &               │ op_BitwiseAnd         │                          │
│ operator |               │ op_BitwiseOr          │                          │
│ operator ^               │ op_ExclusiveOr        │                          │
│ operator ~               │ op_OnesComplement     │ Unary                    │
│ operator ==              │ op_Equality           │                          │
│ operator !=              │ op_Inequality         │                          │
│ operator <               │ op_LessThan           │                          │
│ operator >               │ op_GreaterThan        │                          │
│ operator <=              │ op_LessThanOrEqual    │                          │
│ operator >=              │ op_GreaterThanOrEqual │                          │
│ operator <<              │ op_LeftShift          │                          │
│ operator >>              │ op_RightShift         │                          │
│ operator %               │ op_Modulus            │                          │
│ implicit operator <type> │ op_Implicit           │ Implicit type conversion │
│ explicit operator <type> │ op_Explicit           │ Explicit type conversion │
│ operator true            │ op_True               │                          │
│ operator false           │ op_False              │                          │
└──────────────────────────┴───────────────────────┴──────────────────────────┘

So to retrieve the operator+ method of the DateTime struct, you need to write:

MethodInfo mi = typeof(DateTime).GetMethod("op_Addition",
    BindingFlags.Static | BindingFlags.Public );
Sebastian Krysmanski
  • 8,114
  • 10
  • 49
  • 91
Mohammad Dehghan
  • 17,853
  • 3
  • 55
  • 72
  • 2
    Just curious :) What if I have a static `op_Addition` method with the same signature? – Şafak Gür Nov 03 '12 at 08:33
  • 1
    @ŞafakGür Then you'll get a compiler error saying "Type '' already defines a member called 'op_Addition' with the same parameter types". Because the defined operator method is exactly renamed to aforementioned name, you cannot have both in the same class. – Mohammad Dehghan Nov 03 '12 at 15:23
  • And what would be the naming rule for casting operators? – Grx70 Jan 24 '15 at 08:26
  • 1
    I've managed to find it out myself, but for future reference: casting operators are named `op_Explicit` and `op_Implicit` (I think these names are self-explanatory). Remember though that multiple casting operators can be defined, so one will need to narrow down the search by specifying either parameter type or return type (in respect to the 'direction' of cast). – Grx70 Jan 24 '15 at 09:27
  • 1
    Did you forgot ```~``` ? – Denis535 Sep 03 '18 at 18:55
  • @wishmaster35 Apparently! :) Will add it. – Mohammad Dehghan Sep 04 '18 at 11:47
  • Out of curiosity, did you find this from a book or doc reference or somehow inspect the C# compiler? Thanks! – Christabella Irwanto Nov 30 '20 at 12:59
  • 1
    @ChristabellaIrwanto I remember that I first decompiled a C# code, and later looked up the actual code in the C# compiler. This is not documented anywhere by MS. – Mohammad Dehghan Nov 30 '20 at 13:44
  • 1
    @MohammadDehghan thank you for your valuable insight :) – Christabella Irwanto Nov 30 '20 at 14:01
7
typeof(A).GetMethod("op_Addition").Invoke(null, instance1, instance2);
Cheng Chen
  • 42,509
  • 16
  • 113
  • 174
  • by me, parameters needs to be given via an array `type.GetMethod("op_Subtraction").Invoke(null, new object[] { instance1, instance2 });` – Joseph Merdrignac Jul 27 '19 at 23:29
0

Consider to make your customized operator as property of your Class. And then access the property and its value through reflection.

like

PropertyInfo pinfo = obj.GetType().GetProperty("CustomOperator", BindingFlags.Public | BindingFlags.Instance);
string customOperator = pinfo.GetValue(obj,null) as string;
Talha
  • 18,898
  • 8
  • 49
  • 66