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));
}
}
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.
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.
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.
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.
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.
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