Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make dictionary extension-methods?

I'm trying to write a Dictionary extension that works independently of the data types of Key/Value. I tried pass it by using the object data type, assuming that it will works with any type.

My code:

 public static class DictionaryExtensionsClass
    {
        public static void AddFormat(this Dictionary< ?? unknow type/*object*/, ??unknow type/*object*/> Dic, ??unknow type/*object*/ Key, string str, params object[] arglist)
        {
            Dic.Add(Key, String.Format(str, arglist));
        }
    }
like image 675
Jack Avatar asked Jun 02 '12 15:06

Jack


People also ask

What parameter does an extend () method requires?

Parameters of extend() function in Python The list extend() method has only one parameter, and that is an iterable. The iterable can be a list, tuple (it is like an immutable list), string, set or, even a dictionary.

How do you extend a method in C#?

Select File > New > Project and select Visual C# and Console Application as shown below. Add the reference of the previously created class library to this project. In the above code, you see there is a static class XX with a method, NewMethod. If you notice, the NewMethod takes Class1 as a parameter.

Can we create extension method for interface?

You can use extension methods to extend a class or interface, but not to override them. An extension method with the same name and signature as an interface or class method will never be called. At compile time, extension methods always have lower priority than instance methods defined in the type itself.

What keyword is used to define an extension method?

Extension Method uses the "this" keyword as the first parameter. The first parameter always specifies the type that the method operates on. The extension method is written inside a static class and the method is also defined as static.


1 Answers

You just make the method generic:

public static void AddFormat<TKey>(this Dictionary<TKey, string> dictionary,
    TKey key,
    string formatString,
    params object[] argList)
{
    dictionary.Add(key, string.Format(formatString, argList));
}

Note that it's only generic in the key type as the value would have to be string (or potentially object or an interface that string implements, I guess) given that you're going to add a string value to it.

Unfortunately you can't really express the constraint of "only allow value types where string is a valid value" in a generic type constraint.

like image 111
Jon Skeet Avatar answered Oct 11 '22 10:10

Jon Skeet