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
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 .
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);
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.
The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.
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")
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With