Home C# select Class during Runtime
Reply: 3

C# select Class during Runtime

Griizz
1#
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

Exampel:

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
switch(someInput)
{
case 1:
_problem = new X1();
break;
case 2:
_problem = new X2();
break;
.
.
.
case 610:
_problem = new X610();
break;
}
_promblem?.someFunction();

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
2#
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

try
{

_problem = Assembly.GetExecutingAssembly().CreateInstance($«X{someInput}») as X
}
catch{}
_promblem?.someFunction();
SoronelHaetir
3#
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
4#
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)))
    .ToList();

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]);

instance.SomeFunction();

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