Frustration with generics

Posted by sbi on Stack Overflow See other posts from Stack Overflow or by sbi
Published on 2010-06-18T16:31:33Z Indexed on 2010/06/18 16:43 UTC
Read the original article Hit count: 350

Filed under:
|
|

I have a bunch of functions which are currently overloaded to operate on int and string:

bool foo(int);
bool foo(string);
bool bar(int);
bool bar(string);
void baz(int p);
void baz(string p);

I then have a bunch of functions taking 1, 2, 3, or 4 arguments of either int or string, which call the aforementioned functions:

void g(int p1)    { if(foo(p1)) baz(p1); }
void g(string p1) { if(foo(p1)) baz(p1); }

void g(int    p2, int    p2) { if(foo(p1)) baz(p1); if(bar(p2)) baz(p2); }
void g(int    p2, string p2) { if(foo(p1)) baz(p1); if(bar(p2)) baz(p2); }
void g(string p2, int    p2) { if(foo(p1)) baz(p1); if(bar(p2)) baz(p2); }
void g(string p2, string p2) { if(foo(p1)) baz(p1); if(bar(p2)) baz(p2); }

// etc.

(The implementation of the g() family is just a placeholder. actually they are more complicated.)

More types than the current int or string might have to be introduced at any time. The same goes for functions with more arguments than 4. The current number of identical functions is barely manageable. Add one more variant in either dimension and the combinatoric explosion will be so huge, it might blow away the application.

In C++, I'd templatize g() and be done. I understand that .NET generics are different. <sigh> But I have been fighting them for two hours trying to come up with a solution that doesn't involve too much copy&paste of code. To no avail.
Surely, C#/.NET/generics/whatever won't require me to type out identical code for a family of functions taking five arguments of either of three types?

So what am I missing here?

© Stack Overflow or respective owner

Related posts about c#

Related posts about beginner