Reputation: 86600
I have a generic class Foo<T> where T: SomeBaseType
.
And in the specific case where T
is SpecificDerivedType
, I want my class to have an additional method.
Something like:
class Foo<T> where T: SomeBaseType
{
//.... lots of regular methods taking T, outputting T, etc.
//in pseudo code
void SpecialMethod() visible if T: SpecificDerivedType
{
//...code...
}
}
How can I achieve this?
Upvotes: 5
Views: 372
Reputation: 1500245
There's nothing quite like that, but you could add an extension method on Foo<T>
with a more specific constraint than T
normally has. Here's a complete example:
using System;
class SomeBaseType {}
class SomeDerivedType : SomeBaseType {}
static class FooExtensions
{
public static void Extra<T>(this Foo<T> foo)
where T : SomeDerivedType
{
Console.WriteLine("You have extra functionality!");
}
}
class Foo<T> where T : SomeBaseType
{
}
class Program
{
static void Main(string[] args)
{
Foo<SomeBaseType> foo1 = new Foo<SomeBaseType>();
Foo<SomeDerivedType> foo2 = new Foo<SomeDerivedType>();
// Doesn't compile: the constraint isn't met
// foo1.Extra();
// Does compile
foo2.Extra();
}
}
That allows you to call the method on an existing instance rather than having to create a more specialized instance. On the other hand, it relies on the extension method having enough access to do whatever it needs to in Foo<T>
. You may need to have an unconstrained internal
method in Foo<T>
for FooExtensions.Extra
to call.
Upvotes: 4
Reputation: 203821
Make an extension method for Foo<T>
:
public static void SpecialMethod<T>(this Foo<T> foo)
where T : SpecificDerivedType
{
}
Upvotes: 7
Reputation: 156958
How can I achieve this?
You can't. Create a specialized Foo
.
class SpecialFoo<T> : Foo<T> where T: SpecificDerivedType
{
void SpecialMethod()
{
//...code...
}
}
Other suggest an extension method, which is obviously not the same as what you ask. It might be a workaround though.
Upvotes: 4
Reputation: 4119
You can create an extension method that will look like this:
public static void SpecificMethod<T>(this Generic<T> instance)
where T : SpecificDerivedType
Upvotes: 2