C
C#2mo 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
sibber2mo ago
foo.GenericMethod<Bar>
Holipop
Holipop2mo 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
sibber2mo 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
Holipop2mo ago
Gotcha gotcha, thank you lots!
sibber
sibber2mo ago
np $close
MODiX
MODiX2mo ago
If you have no further questions, please use /close to mark the forum thread as answered
SleepWellPupper
SleepWellPupper2mo ago
The pattern is called CRTP if you want to read more about it.
Want results from more Discord servers?
Add your server
More Posts