C # overloading common functions with various parameter restrictions

I have the following functions:

public static V AddIfNotPresent<K, V>( this Dictionary<K, V> store, K key ) where V : new() public static V AddIfNotPresent<K, V>( this Dictionary<K, V> store, K key ) 

First, is it possible to overload functions this way?

If overloading is not possible, I can be more specific with my functions and tools:

 public static string Foo<K, string>( this Dictionary<K, string> store, K key ) 

Like a little History I have a dictionary with string values, and I would live a sequential extension of the "Foo" Dictionary to allow me to add new () objects or an empty string (depending on the situation).

+4
source share
1 answer

No, you cannot overload the type parameters with restrictions. But yes, you can overload the number of parameters like:

 public static string Foo<TKey>(this Dictionary<TKey, string> store, TKey key) 

(Note that string not part of the generic type parameter list for Foo; it is not a type parameter itself, it is simply used as a type argument for Dictionary .)

+4
source

Source: https://habr.com/ru/post/1341617/


All Articles