I have a function which initiates commands for a command class. Since there are many commands to initiate, writing code for each one would be tedious.

The function definition is as follows-

private static void InitCommand(KeyGesture input, String text, String name)
        {
            InputGestureCollection inputs = new InputGestureCollection();
            inputs.Add(input);

            Type t = typeof(UploadCommands);
            t.GetMember(name);
            
            (RoutedUICommand)t.GetMember(name) = new RoutedUICommand(text, name, typeof(UploadCommands), inputs);
        }

Now, my problem is that I wish to reference the commands dynamically. I pass in the command name, it references the public static RoutedUICommand variable.

In PHP, the equivalent would be-

$class->$member = "Blah, blah";

I can't figure out how this would be done in C#.

Recommended Answers

All 4 Replies

Are you referring to a class field in C#?
Then use property syntax to access it.
Your code looks a bit strange, why are you making a inputs collection and just put one item input into it?

In PHP, the equivalent would be-

$class->$member = "Blah, blah";

I can't figure out how this would be done in C#.

Hi Ishbir,

.NET have this feature. It is called Reflection in .NET.

You can use reflection to dynamically create an instance of a type(class), bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties.

Refer this link and also the link given by adatapost.

commented: very good suggestion. +6
commented: reflection is my recommended approach +6

You may also consider using an enumeration member to define all of your commands. This way you have a strongly typed way to reference the command. You can call .ToString() on the enumeration member and call Enum.Parse() :

internal enum CommandTypes
    {
      Command1 = 1,
      Command2 = 2
    }
    private void button2_Click(object sender, EventArgs e)
    {
      CommandTypes cmd = CommandTypes.Command2;
      string sCmdString = cmd.ToString();
      Console.WriteLine("cmd string value: " + sCmdString);
      Console.WriteLine("cmd int value: " + ((int)cmd).ToString());
      CommandTypes parsedCmd = (CommandTypes)Enum.Parse(typeof(CommandTypes), sCmdString);
      System.Diagnostics.Debugger.Break();
    }

Results in:

cmd string value: Command2
cmd int value: 2

You could then go on to design an attribute and use the enumeration member in your attribute for the class member that represents the command.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.