0

C# does not support template specialization. Is there a workaround? I am interested in achieving something similar to the c++ code below.

Thank you

    class C
    {
    public:
        template< typename T > void f() {} // no parameter function
        template<> void f<double>() {} // no parameter function
    };
cassandrad
  • 3,412
  • 26
  • 50
CFlat
  • 61
  • 5
  • 1
    Does this answer your question? [How to do template specialization in C#](https://stackoverflow.com/questions/600978/how-to-do-template-specialization-in-c-sharp) – Wyck Apr 28 '20 at 14:34
  • @Wyck No, it does not answer. `T` is not a method argument. – CFlat Apr 28 '20 at 14:46
  • 1
    For those who don't read C++ on a regular basis but who might know a fair deal about C# features, can you explain *what* the C++ code achieves? – Damien_The_Unbeliever Apr 28 '20 at 15:20
  • @Damien_The_Unbeliever This is just an example. The actual code is complex. I cannot think of a different example. – CFlat Apr 28 '20 at 17:57

1 Answers1

1

No, that's not possible, you have to use dynamic dispatching

public class C
{
    public int DoWork<T>()
    {
        if (typeof(T) == typeof(int))
            return DoWorkInt();

        return 13;
    }
    private int DoWorkInt() { return 42; }
}

C# does not support explicit specialization; that is, a custom implementation of a template for a specific type.

From Differences Between C++ Templates and C# Generics

cassandrad
  • 3,412
  • 26
  • 50