Reputation: 150
Is it possible in C# to define a generic method in a base class and then have the type be defined based on what subclass is calling it.
abstract class BaseClass
{
void SomeMethod<T>()
{
...
}
}
class SubClass1 : BaseClass
{
...
}
class SubClass2 : BaseClass
{
...
}
Now if i call SomeMethod from an instance of SubClass1 I want it to use one type (let's say string) and if i call it from an instance of SubClass2 I want it to use a different type (let's say int). So...
BaseClass instance1 = new SubClass1();
BaseClass instance2 = new SubClass2();
instance1.SomeMethod() //this should call SomeMethod<string>()
instance2.SomeMethod() //this should call SomeMethod<int>()
Is this possible?
I would like to have one BaseClass variable be assigned an instance of either SubClass1 or SubClass2:
for (int i = 0; i < numSubClasses; i++)
{
BaseClass variable = GetNextSubClass(); //On first iteration GetNextSublass returns an instance of SubClass1 and on second iteration it returns an instance of SubClass2
variable.SomeMethod();
}
The reason I want to have a generic implementation in the base class is because the implementation for the two sub classes would be exactly the same except for the type
Upvotes: 0
Views: 127
Reputation: 1334
Add the generic type to the Base class:
abstract class BaseClass<T>
{
void SomeMethod<T>()
{
...
}
}
class SubClass1 : BaseClass<string>
{
...
}
class SubClass2 : BaseClass<int>
{
...
}
The above code is a bit pointless as we are not making use of the generic types.
abstract class BaseClass<T>
{
public T SomeMethod<T>(T aParam)
{
...
return aParam;
}
}
class SubClass1 : BaseClass<string>
{
...
}
class SubClass2 : BaseClass<int>
{
...
}
Providing a bit more concrete example of what you want to achieve will be helpful though.
Upvotes: 3
Reputation: 869
It looks like you want to use generic interface:
using System;
class Program
{
interface IBase<T>
{
void SomeMethod();
}
class SubClass1 : IBase<string>
{
public void SomeMethod()
{
Console.WriteLine("I write string!");
}
}
class SubClass2 : IBase<int>
{
public void SomeMethod()
{
Console.WriteLine("I write int!");
}
}
static void Main(string[] args)
{
IBase<string> instance1 = new SubClass1();
IBase<int> instance2 = new SubClass2();
instance1.SomeMethod(); //this should call SomeMethod<string>()
instance2.SomeMethod(); //this should call SomeMethod<int>()
Console.ReadLine();
}
}
In fact, you don't even need 2 classes. You could use a single generic class for the same effect:
using System;
class Program
{
interface IBase
{
void SomeMethod();
}
class SubClass<T> : IBase
{
public void SomeMethod()
{
Console.WriteLine("I write {0}", typeof(T));
}
}
static void Main(string[] args)
{
IBase instance1 = new SubClass<string>();
IBase instance2 = new SubClass<int>();
instance1.SomeMethod(); //this should call SomeMethod<string>()
instance2.SomeMethod(); //this should call SomeMethod<int>()
Console.ReadLine();
}
}
Upvotes: 0