Hi Don,

all instances of a generic type are based on the same IL code. In case of
your example you'd need different IL codes depending on what T is.

If T is a primitive type, a + b needs IL code like that:

ldloc.0
ldloc.1
add

If T is a class with an operator +  you'll need code like that:

ldloc.0
ldloc.1
call  class T T::op_Addition (class T, class T)

This might be why your code is failing to compile.

I also found there seems to be no way to invoke a static function of a
parameter type:

public class A <T>
{
  public void f()
  {
    T.StaticFunc(); // error
  }
}

Since operators are static functions there seems to be no way to invoke
operators of parameter types.

If you decided to only support class types and tried to solve the problem
that way:

using System;

public class AppRunner
{
 public static void Main()
 {
  SomeMath<MyInt> s = new SomeMath<MyInt>();
  Console.WriteLine(s.Add(new MyInt(1),new MyInt(2)));
 }


 private class SomeMath <T>
 {
  public T Add (T val, T val2)
  {
   T ret = val.InternalAdd(val2); // instead of val + val2
   return val;
  }
 }
}

you'd end up with an error either. To get it working you need an Interface:

public interface IAddable <T>
{
 T InternalAdd (T val);
}

and declare T as an IAddable:

 private class SomeMath <T> where T : IAddable <T>
.... (see below for full code)

This works but doesn't look like nifty code....


Regards
Mirko


// working code

using System;

public class AppRunner
{

 private interface IAddable <T>
 {
  T InternalAdd (T val);
 }

 private class MyInt : IAddable<MyInt>
 {
   int i;
   public MyInt(int v) { i = v; }
   public MyInt InternalAdd (MyInt val)
   {
     return new MyInt(i + val.i);
   }
 }

 public static void Main()
 {
  SomeMath<MyInt> s = new SomeMath<MyInt>();
  Console.WriteLine(s.Add(new MyInt(1),new MyInt(2)));
 }


 private class SomeMath <T> where T : IAddable <T>
 {
  public T Add (T val, T val2)
  {
   return val.InternalAdd(val2);
  }
 }
}

Reply via email to