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 }; 
4
  • 1
    Does this answer your question? How to do template specialization in C# Commented Apr 28, 2020 at 14:34
  • @Wyck No, it does not answer. T is not a method argument. Commented Apr 28, 2020 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? Commented Apr 28, 2020 at 15:20
  • @Damien_The_Unbeliever This is just an example. The actual code is complex. I cannot think of a different example. Commented Apr 28, 2020 at 17:57

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.