I did an experiment in C#, first I created a class library called "ClassLibrary1", with code below:
public class ClassLibrary1
{
public static void f()
{
var m = new { m_s = "abc", m_l = 2L };
Console.WriteLine(m.GetType());
}
}
Note, I removed namespace information generated by IDE. Then I created console application with code below:(also removed namespace) while referring to ClassLibrary1:
class Program
{
static void Main()
{
var m = new {m_s = "xyz", m_l = 5L};
Console.WriteLine(m.GetType());
ClassLibrary1.f();
}
}
I run the program, it prints:
<>f__AnonymousType0`2[System.String,System.Int64]
<>f__AnonymousType0`2[System.String,System.Int64]
Press any key to continue . . .
The output indicates that the 2 anonymous classes defined in class library and console application are having identical class type.
My question is: how does C# binary store its type information for all the classes it contains? If it's stored in a global place, when the exe is built with dll reference, 2 same anonymous type information is there, so
(1) Is name duplication an error that should be avoid?
(2) If not an error like I tested, how could C# binary store duplicate type information?
(3) And in runtime, what's the rule to look up type information to create real objects?
Seems a bit confusing in my example. Thanks.
It is possible to have duplicate names in the .NET assembly, because metadata items (classes, fields, properties etc) are referenced internally by numeric metadata token, not by the name
Although the use of duplicate names is restricted in ECMA-335 (except several special cases), this possibility is exploited by a number of obfuscators, and, probably, by the compilers in cases when the name of the metadata item (class in your case) is not directly exposed to the user code
EDIT: CodeCaster is right with his answer, the names reside in different assemblies in your case, hence the duplicate names. Though I believe my point with having duplicate names in the same assembly is valid, but may not be applicable to this particular question.