Reputation: 6359
I needed to serialize KeyValuePair and I found the solution here:
Is there a serializable generic Key/Value pair class in .NET?
So I used the accepted answer for that question which said all you need is to define class/struct like this
public class KeyValuePair<K,V>
{
public K Key {get;set;}
public V Value {get;set;}
}
This works but now there are 2 generic classes with same name. The custom class above and the one from System.Collections.Generics
namespace.
So how does the compiler know which one to use when there is a code like this
myList=new List<KeyValuePair<string, string>>();
One has signature KeyValuePair<K,V>
and the other is KeyValuePair<TKey,TValue>
, so both have same number of Type Parameters.
Why does the code compile with no errors?
Upvotes: 0
Views: 73
Reputation: 709
Check out the "using" directives in your file. As you stated, the classes reside in different namespaces, so your class might be explicitly using one of them, which rids the compiler of the dilemma.
Upvotes: 0
Reputation: 60236
Name, namespace an generic type parameters are unique per assembly. Nothing prevents you from creating another type like you do it, but the compiler will not be able to figure out which one to use if yet another project uses both assemblies (the system one and yours).
Another variant of the same problem occurs when two same assemblies with different versions are in use, the compiler will pick and bind to one which can cause painful a debugging experience (it looks as if the types shoud match but they don't - the framework itself has no problem with it though).
Note that you cannot replace a type in another assembly by "redefining" is like this.
Upvotes: 1
Reputation: 1502216
When the C# compiler sees a name that it needs to resolve, it follows the steps in the specification - the rules are in sections 3.8 ("namespace-or-type-name") and 7.6.2 ("simple names").
It's all about context:
I would personally recommend against reusing a name which is also in the framework in a commonly-used namespace... it will make it harder to refer to both types from within the same section of code. But it doesn't actually cause the compiler any issues.
Upvotes: 3