© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
9 replies
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
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

❔ Generics
C#CC# / help
3y ago
Generics question
C#CC# / help
2y ago
Just learned generics...
C#CC# / help
17mo ago
Help with Generics
C#CC# / help
2y ago