2

It's not a problem to use MakeArrayType() if we want to make a array type of a specific type, for example, the char array:

typeof(char).MakeArrayType()

Of course it's more intuitive to use typeof(char[]) instead.

And the property Assembly of a type tells us what the assembly where the type is.

So the following code should be a reasonable example to find a type in an assembly:

var chars=new[] { '\x20' };
var typeofCharArray=chars.GetType();
var assembly=typeofCharArray.Assembly;
var doesContain=assembly.GetTypes().Contains(typeofCharArray);

But doesContain says it DOESN'T, it's false. This happens regardless the array type is from MakeArrayType() or typeof(), or an instance's GetType.

There's a doubt that it was forwarded to other assemblies that I've read from Assembly.GetTypes. And I tried:

var assemblyContainsTypeOfCharArray=(
        from it in AppDomain.CurrentDomain.GetAssemblies()
        let types=it.GetTypes()
        where types.Contains(typeof(char[]))
        select it).FirstOrDefault();

The interesting thing is assemblyContainsTypeOfCharArray is null.

Where are the array types?

Ken Kin
  • 4,503
  • 3
  • 38
  • 76

1 Answers1

5

Simply: GetTypes() returns the types that are actually declared in that assembly. The array types are... not. They claim to be from there, but that is just returning the element-type's Assembly information. The array type isn't actually declared in there (it isn't actually declared anywhere - it is an invention of the JIT, on-the-fly).

So basically: the array type lies. Shame on it.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • 1
    The `abstract` type `System.Array` belongs to `mscorlib.dll`. Clearly `GetType()` will return a concrete type. The type `System.Uri` is defined in `System.dll`. Does anyone know what `typeof(Uri[]).Assembly` returns? – Jeppe Stig Nielsen Jul 29 '13 at 19:56
  • 1
    @JeppeStigNielsen it will return whatever `typeof(System.Uri).Assembly` returns - i.e. `System.dll`; I suspect that this is to assist in things like serialization, access validation, and other code that wants to know what assembly something comes from. It kinda is sorta almost true, in a manner of thinking. – Marc Gravell Jul 29 '13 at 19:59
  • But `typeof(List).Assembly` is required to always return `mscorlib` if I read the spec correctly, so that might lead to confusion. But clearly a call `assembly.GetTypes()` can never return all *constructed* types `List`, only the generic definition `List<>`. Just for an analogy. – Jeppe Stig Nielsen Jul 29 '13 at 20:04