Home C# select Class during Runtime
Reply: 3

C# select Class during Runtime

Griizz Published in 2018-01-12 18:01:26Z

I have a C# Project for ProjectEuler if you know that.

For that i use a abstract class lets call it 'X'

public abstract class X {
protected abstract void SomeFunction()

There are over 600 problems to solve in this project. For every problem, I create a class that inherits from X. The name of the class is always the 'Baseclassname' followed by a number


public class X2 : X {
public override void SomeFunction()

During runtime, I choose via consoleinput a problem by entering a valid integer. This integer goes into a switch and creates the corresponding problem and executes someFunction if '_problem' is unequal to null.

X _problem = null;
int someInput; //any valid input readin via Console
case 1:
_problem = new X1();
case 2:
_problem = new X2();
case 610:
_problem = new X610();

So my question to the community is how to avoid a switch case with over 600 cases. Is there a better solution to do this?

I hope this question is written well cos it's my first. :)

Edit: Some 'key, value' Pair array would only be ideal if all existing pairs get added automatically during compilation.

Surjit SD
Surjit SD Reply to 2018-01-12 18:22:00Z

Try reflection as following;

X _problem = null;
int someInput; //any valid input readin via Console


_problem = Assembly.GetExecutingAssembly().CreateInstance($«X{someInput}») as X
SoronelHaetir Reply to 2018-01-12 18:16:18Z

If the names are well-formed (that is you can generate the class name from input) it would be easy to use System.Reflection.Assembly's CreateInstance method and then cast to your abstract type and acallthe base member.

DavidG Reply to 2018-01-12 18:27:26Z

Here's a skeleton of what you could do with a menu of choices for the user:

//Get all the types that inherit from 'X'
var types = Assembly.GetExecutingAssembly().GetTypes()
    .Where(t => t.IsClass && !t.IsAbstract && t.IsSubclassOf(typeof(X)))

Console.WriteLine("Choose a class to run");
var index = 0;
foreach (var type in types)
    Console.WriteLine($"{index++}: {type.Name}");

Console.Write("Enter number: ");

//Much better to use "TryParse" here and validate the input
index = int.Parse(Console.ReadLine());

var instance = (X)Activator.CreateInstance(types[index]);


Note, you will have to change the protection level to public to get this working.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.306817 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO