Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String- Function dictionary c# where functions have different arguments

Basically I'm trying to make a string to function dictionary in c#, I've seen it done like this:

Dictionary<string, Func<string, string>>

However the issue is that the functions I want to put into my dictionary all have different amounts of arguments of different types. Therefore how do I make a dictionary that will do this?

Adam

like image 217
RoboPython Avatar asked Mar 11 '15 16:03

RoboPython


People also ask

What is IDictionary C#?

The IDictionary<TKey,TValue> interface is the base interface for generic collections of key/value pairs. Each element is a key/value pair stored in a KeyValuePair<TKey,TValue> object. Each pair must have a unique key. Implementations can vary in whether they allow key to be null .

How do you check if a value is present in a dictionary C#?

ContainsValue() Method. This method is used to check whether the Dictionary<TKey,TValue> contains a specific value or not. Syntax: public bool ContainsValue (TValue value);

How does C# dictionary work?

A dictionary, also called an associative array, is a collection of unique keys and a collection of values, where each key is associated with one value. Retrieving and adding values is very fast. Dictionaries take more memory because for each value there is also a key.

Can dictionary have duplicate keys C#?

The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.


1 Answers

You can define your own delegate taking a params string[] argument, like this:

delegate TOut ParamsFunc<TIn, TOut>(params TIn[] args);

And declares your dictionary like so:

Dictionary<string, ParamsFunc<string, string>> functions;

So, you can use it like this:

public static string Concat(string[] args)
{
    return string.Concat(args);
}

var functions = new Dictionary<string, ParamsFunc<string, string>>();
functions.Add("concat", Concat);

var concat = functions["concat"];

Console.WriteLine(concat());                                //Output: ""
Console.WriteLine(concat("A"));                             //Output: "A"
Console.WriteLine(concat("A", "B"));                        //Output: "AB"
Console.WriteLine(concat(new string[] { "A", "B", "C" }));  //Output: "ABC"

Be aware that you still need to declare your methods with a string[] argument, even if you only need one string parameter.

On the other hand, it can be called using params style (like concat() or concat("A", "B")).

like image 161
Arturo Menchaca Avatar answered Sep 21 '22 15:09

Arturo Menchaca