Home > Back-end >  C# Identify class based on string variable
C# Identify class based on string variable

Time:10-17

I'm am a very new to c# and been watching and doing some tutorials. I managed to build a simple console guessing game. However now I want to go a little bit beyond the tutorial but I run in to issues and don't seem to get the answer from google or youtube unfortunately...

So I have created a new class called SecretWord and populated this with "secret1" and "secret2" with a word and a few clues.

Then I put this in to array and randomize a number based of the entries in the class to return either "secret1" or "secret2" I then want to populate my hint method with the respective secret{X}.hint1 value but when I try to select it and just console write it I get an error.

So the question is, how do I call my class with the secretClass variable containing the class name?

Thank you in advance and helping me learn! :)

 SecretWord secret1 = new SecretWord("Ape", "It's an animal.", "It climbs trees.", "Planet of the ...", "Looks like human.");
        SecretWord secret2 = new SecretWord("Dog", "It has four legs", "It barks", "Man's best friend", "Woof woof");

        Random rnd = new Random();
        int randSecretKey = rnd.Next(1, SecretWord.secretCount);

        string secretClass = "secret"   randSecretKey;

        Console.WriteLine(secretClass.hint1);

CodePudding user response:

If I understood your question correctly. You variables like secret1 and secret2. And you are generating string variable which value can be equal to the variable names, and you want to access these variables now, right ?

You can do some work around to solve this issue.

You can define properties in this class with name secret1 of type SecretWord. And with use of reflection you can access them by name. Example is below.

this.GetType().GetField("secret1").GetValue(

You can also use GetProperty method.

  • Related