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

Edited 7 Years Ago by Ishbir: n/a

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?

Edited 7 Years Ago by ddanbe: n/a

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.

Comments
reflection is my recommended approach
very good suggestion.

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.

This article has been dead for over six months. Start a new discussion instead.