Home > Net >  Best way to use = (add and assign) and -= (subtract and assign) operators on generic type without h
Best way to use = (add and assign) and -= (subtract and assign) operators on generic type without h

Time:12-14

My application uses objects of type Tag<T> where the Tag property Value is of type T. The application interprets a custom script language into C#. I can assign Tag Value after the interpretation when the exact type of the Tag is known:

Tag<int> myTag = new Tag<int>();
myTag.Value  = 10; //this works

However, I would like to encapsulate all the value assignment methods into a layer above, before the interpretation happens. At that point, the tag type is unknown (generic). Therefore I would like to assign values before knowing the exact tag type:

Tag<T> myTag = new Tag<T>();
myTag.Value  = 10; //this doesn't : CS0019  C# Operator ' =' cannot be applied to operands of type 'T' and 'T'

Of course, = and -= only work for certain types like int and string. So, I would have to add a switch or if and then decide what operator to use based on the type. But this seems like a brute force workaround and doesn't really satisfy me. Is there maybe a more elegant workaround or a best practice?

I tried googling but the closest answer I could find is for the operator ==

public bool Compare<T>(T x, T y) 
{ 
    return EqualityComparer<T>.Default.Equals(x, y); 
}

I am expecting something along these lines.

CodePudding user response:

In C# 11 / .NET 7:

    static void Main()
    {
        Console.WriteLine(Foo(1,5,3)); // 2
    }
    static T Foo<T>(T x, T y, T z) where T : INumber<T>
    {
        return (x   y) / z;
    }

CodePudding user response:

While overloaded operators are always static in C# (and here it is explained why), we have to declare them specifically for all your custom types:

public class MyType
{
    public static MyType operator  (MyType a, MyType b)
    {
        // some logic for   operation
        return something;
    }
}

So now you are free to use it as usual:

MyType a = new();
MyType b = new();
var c = a   b;
  • Related