C
C#9mo ago
DeadlyRemix

❔ Generics

I want to start off by saying I have no clue what I'm talking about. With that out of the way I have a generic function that I want pass a type into, but I want to store that type in a variable and let it be subject to change. Below is an example in a console application which definitively doesn't work, but it demonstrates how I would want it to work.
Random randomClass = new Random();
List<Type> aList = new List<Type> { new A(), new B(), new C() };
int randomInteger = randomClass.Next(3);
Type type = aList[randomInteger];
typeFunc<type>();
static void typeFunc<T>() where T : A
{
Console.WriteLine("This worked");
}

public class A
{

}
public class B : A
{

}
public class C : A
{

}
Random randomClass = new Random();
List<Type> aList = new List<Type> { new A(), new B(), new C() };
int randomInteger = randomClass.Next(3);
Type type = aList[randomInteger];
typeFunc<type>();
static void typeFunc<T>() where T : A
{
Console.WriteLine("This worked");
}

public class A
{

}
public class B : A
{

}
public class C : A
{

}
How is this done? Thanks
9 Replies
reflectronic
reflectronic9mo ago
you have to use reflection. it is not easy
DeadlyRemix
DeadlyRemix9mo ago
ok i'll look into it ty
reflectronic
reflectronic9mo ago
typeof(X).GetMethod("typeFunc", ...).MakeGenericMethod(aList[randomInteger]).Invoke(thisObject, new[] { parameter1, });
typeof(X).GetMethod("typeFunc", ...).MakeGenericMethod(aList[randomInteger]).Invoke(thisObject, new[] { parameter1, });
DeadlyRemix
DeadlyRemix9mo ago
thank you i'll try and get to grips with this. also if i make a list like this
List<A> aList = new List<A> { new A(), new B(), new C() };
List<A> aList = new List<A> { new A(), new B(), new C() };
is it automatically casted to A and if so that means I lose infomation on what type it is right? and if so how would I store it instead? sorry for so many questions in one
reflectronic
reflectronic9mo ago
you do not lose the type information permanently. for example, aList[0] is B would be false, but aList[1] is B would be true
DeadlyRemix
DeadlyRemix9mo ago
oh ok
reflectronic
reflectronic9mo ago
you can also do aList[1].GetType() to get typeof(B), which you can do other comparisons with
DeadlyRemix
DeadlyRemix9mo ago
ok thank you
Accord
Accord9mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.