Search code examples
c#coding-style

How to implement functions like template in C#


How can I implement functions like template in C#? For example, FuncA, FuncB, and FuncC functions take the same arguments, and then those functions always just do the same operation with ClassA. Even if those function take ClassB or three integers, those function convert ClassB or three integers into ClassA to do the same operation as when taking the ClassA as an argument. I am not sure if there is a good way, but if you know, please let me know.

void FuncA(ClassA a)
{
    // do something
}
void FuncA(ClassB b)
{
    FuncA(b.ToA());
}
void FuncA(int x, int y, int z)
{
    FuncA(new ClassA(x, y, z));
}

void FuncB(ClassA a)
{
    // do something
}
void FuncB(ClassB b)
{
    FuncB(b.ToA());
}
void FuncB(int x, int y, int z)
{
    FuncB(new ClassA(x, y, z));
}

void FuncC(ClassA a)
{
    // do something
}
void FuncC(ClassB b)
{
    FuncC(b.ToA());
}
void FuncC(int x, int y, int z)
{
    FuncC(new ClassA(x, y, z));
}

// FuncD, FuncE and so on...

Solution

  • I solved this problem by using implicit conversion and tuple.

    class ClassA
    {
        // members...
    
        public static implicit operator ClassA(ClassB b)
        {
            return b.ToA();
        }
    
        public static implicit operator ClassA(Tuple<int, int, int> t)
        {
            return new ClassA(t.Item1, t.Item2, t.Item3);
        }
    }
    
    void FuncA(ClassA a)
    {
        // do something
    }
    // we don't have to implement overloaded FuncA functions that take ClassB or three integers.
    void FuncB(ClassA a) { /* do something */ }
    void FuncC(ClassA a) { /* do something */ }