C
C#10mo ago
holipop

Getting the typeof this to use in a generic method

I have a class with a method that requires a different class that has a generic method. How can I get the type of the first class to pass into the generic method?
public class Foo
{
void GenericMethod<T> () {}
}

public class Bar
{
void Pass (Foo foo)
{
// I want to get Bar to use as T but I'm unsure how to search for this problem and this doesn't work.
Type T = this.GetType();
foo.GenericMethod<T>();
}
}
public class Foo
{
void GenericMethod<T> () {}
}

public class Bar
{
void Pass (Foo foo)
{
// I want to get Bar to use as T but I'm unsure how to search for this problem and this doesn't work.
Type T = this.GetType();
foo.GenericMethod<T>();
}
}
7 Replies
sibber
sibber10mo ago
foo.GenericMethod<Bar>
holipop
holipopOP10mo ago
If I have any class that extends Bar, will they have to override the method to pass their own type in or no? like if I had.. class Thing : Bar for context, I want Bar to be an abstract class and for anything that inherits it to have Pass work
sibber
sibber10mo ago
ah generally the solution for that is this:
public class Bar<T> where T : Bar<T>
{
bla bla
foo.GenericMethod<T>();
}
public class Bar<T> where T : Bar<T>
{
bla bla
foo.GenericMethod<T>();
}
its not a perfect solution since you could pass another T that inherits bar but its the best you can do in C# for now
holipop
holipopOP10mo ago
Gotcha gotcha, thank you lots!
sibber
sibber10mo ago
np $close
MODiX
MODiX10mo ago
If you have no further questions, please use /close to mark the forum thread as answered
SleepWellPupper
SleepWellPupper10mo ago
The pattern is called CRTP if you want to read more about it.

Did you find this page helpful?