specialized generic method in C#

M

My interest

Can I create a specialized generic method depends on the constraint on
the generic type constraint? such as:

static class foo
{
public static void f<T_>(T_ dummy) where T_: struct { ....}
public static void f<T_>(T_ dummy) where T_: class { ....}
}

Thanks.
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

Did you try to compile it?

It gives an error "Type 'foo' already defines a member called 'f' with the
same parameter types" which says basically that you need to have a
difference in parameters set between the methods.
 
M

My interest

Yes, I know the compiler will generate this error message. What I try
to ask is how can I get around with this if I want different f() being
called for different type of parameter (e.g. overloading) .. by
putting a where constraint.

For example, in a non-generic world, this is valid:

static class foo
{
public static void f(double dummy) { ....}
public static void f(Array dummy) { ....}
}

Can I do sth similar in the generic world? I guess one way is just to
create one f() and do dispatch inside the code by checking
tyeof(dummy), but it will be very messy / inconvenient. So I am
trying to seek an alternatively approach.
 
J

Jon Skeet [C# MVP]

My interest said:
Yes, I know the compiler will generate this error message. What I try
to ask is how can I get around with this if I want different f() being
called for different type of parameter (e.g. overloading) .. by
putting a where constraint.

For example, in a non-generic world, this is valid:

static class foo
{
public static void f(double dummy) { ....}
public static void f(Array dummy) { ....}
}

Can I do sth similar in the generic world? I guess one way is just to
create one f() and do dispatch inside the code by checking
tyeof(dummy), but it will be very messy / inconvenient. So I am
trying to seek an alternatively approach.

No, you can't overload by type constraints (which is effectively what
you're trying to do).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top