user1823701
user1823701

Reputation: 541

How to run a string method?

This is what I want to have:

static void A(string s)
{
    //Code Here...
}
static void B(string s)
{
    //Code Here...
}
static void C(string s)
{
    //Code Here...
}
static void Main(string[] args)
{
      string temp = Console.ReadLine();
      string[] s = temp.Split(' ');
      if (s[0] == "A")
          A(s[1]);
      if (s[0] == "B")
          B(s[1]);
      if (s[0] == "C")
          C(s[1]);
}

But when I have a lot of methods it does'nt work very well...

Is there another way to do this?

Upvotes: 1

Views: 207

Answers (7)

Matthew Watson
Matthew Watson

Reputation: 109567

Sometimes you can use a Dictionary of Actions to map strings to methods:

using System;
using System.Collections.Generic;

namespace Demo
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            _actions = new Dictionary<string, Action<string>>();

            _actions["A"] = A;
            _actions["B"] = B;
            _actions["C"] = C;

            string[] s = Console.ReadLine().Split(' ');

            if (!processArg(s[0], s[1]))
            {
                // Argument wasn't in the list. Do error handling.
            }
        }

        static bool processArg(string name, string value)
        {
            Action<string> action;

            if (_actions.TryGetValue(name, out action))
            {
                action(value);
                return true;
            }

            return false;
        }

        static void A(string s)
        {
            Console.WriteLine("A: " + s);
        }

        static void B(string s)
        {
            Console.WriteLine("B: " + s);
        }

        static void C(string s)
        {
            Console.WriteLine("C: " + s);
        }

        private static Dictionary<string, Action<string>> _actions;
    }
}

Upvotes: 1

yurik256
yurik256

Reputation: 86

You can write something like this.

private static void Main(string[] args)
    {
        InitializeFunctions();

        string temp = Console.ReadLine();
        string[] s = temp.Split(' ');

        _functions[s[0]].Invoke(s[1]);
    }

    private static void InitializeFunctions()
    {
        _functions.Add("A",A);
        _functions.Add("B",B);
        _functions.Add("C",C);
    }

    private static Dictionary<string, Func> _functions = new Dictionary<string, Func>();

    public delegate void Func(string process);

    static void A(string s)
    {
        //Code Here...
    }
    static void B(string s)
    {
        //Code Here...
    }
    static void C(string s)
    {
        //Code Here...
    }

If you will have new method with the same signature just add it to _functions dictionary in InitializeFunctions method.

Upvotes: 1

Parvathy
Parvathy

Reputation: 2455

This code will work for all methods may be your input is not correct or you want to execute multiple methods.

For eg:

if you are reading the following line from console then

A Abcdefg

after split s[0] will be "A" and s[1] will be "Abcdefg",

if you are reading the following line from console then

A abcdef B bhfhhhfh C chgghh

after split s[0]= "A", s[1]="abcdef " s[2]= "B", s[3]="bhfhhhfh " s[4]= "C", s[5]="chgghh"

In this case only A(String) will invoke because you are only checking s[0] and s[1]

if you want to invoke all methods execute it in loop

for(int i=0;i<s.length;i=i+2){
  if (s[i] == "A")
          A(s[i+1]);
      if (s[i] == "B")
          B(s[i+1]);
      if (s[i] == "C")
          C(s[i+1]);
} 

EDIT If you don't want to write if then you can use switch

switch (s[0]) { case "A": A(s(1)); break; case "B": B(s(1)); break; case "C": C(s(1)); break; . . . . . .

}

Upvotes: 0

Pieter Geerkens
Pieter Geerkens

Reputation: 11883

Try this:

    static void A(string s)
    {
        //Code Here...
    }
    static void B(string s)
    {
        //Code Here...
    }
    static void C(string s)
    {
        //Code Here...
    }
    public struct ActionStruct {
      public string String;
      public Action<string> Action;
      public ActionStruct(string s, Action<string> a) : this() {
        String = s; Action = a;
      }
    }
    void Main(string[] args) {
      var actions = new List<ActionStruct>() {
        new ActionStruct("A", s => A(s)),
        new ActionStruct("B", s => B(s)),
        new ActionStruct("C", s => C(s))
      };
      var action = actions.Where(a=>a.String == args[0]).FirstOrDefault();
      if (action.String!= "") action.Action(args[1]);
    }

Upvotes: 0

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391336

There are two ways I would handle this particular problem:

  1. Use a switch statement
  2. Use reflection

Switch statement

In this case you would organize the code like this:

switch (s[0])
{
    case "A":
        A(s(1));
        break;

    case "B":
        B(s(1));
        break;

    // and so on
}

** Using reflection **

If you want to call a method by name, getting the name from a string, you'll have to use reflection:

MethodInfo method = typeof(Program).GetMethod(s(0)); // guessing "Program" here
if (method != null)
    method.Invoke(null, new object[] { s(1) });

However, I would not do this using input from the user, this is like an SQL injection attack, only much worse.

Upvotes: 0

keyboardP
keyboardP

Reputation: 69372

Without more details of what you're trying to do, a basic alternative could be to have one method and use a switch statement.

static void PerformAction(string method, string cInput)
{
    switch(method)
    {
       case "A":                   
              //code
              //something with cInput
              break;
       case "B":
              //code
              break;
       //..
       default:
              //default action code                  
    }    

}

and call it like this

string temp = Console.ReadLine();
string[] s = temp.Split(' ');
PerformAction(s[0],s[1]);

Upvotes: 0

Micka
Micka

Reputation: 1834

What you want to use is something like this.

typedef void (*FuncType)();

std::map<char, FuncType> Fonctions;

Fonctions['A'] = &FonctionA;
...
Fonctions['Z'] = &FonctionZ;

Fonctions[s[0]](s[1]);

You also have to check is the Function[s[0]] is defined.

Upvotes: 0

Related Questions