Type.GetType on struct type

M

marco_segurini

Hi,

I am wondering why 'Type.GetType' has a different behaviour if called
with a user defined struct or a .NET struct (i.e.
System.Drawing.Point).

Example:

using System;

namespace nsGetType
{
struct MyStruct
{
}

class Class1
{
[STAThread]
static void Main(string[] args)
{
Console.WriteLine("Type is [{0}]",
Type.GetType("System.Drawing.Point"));

Console.WriteLine("Type is [{0}]",
Type.GetType("nsGetType.MyStruct"));
}
}
}

Output:

Type is []
Type is [nsGetType.MyStruct]


Thanks for any help.

Marco.
 
J

Jon Skeet [C# MVP]

marco_segurini said:
I am wondering why 'Type.GetType' has a different behaviour if called
with a user defined struct or a .NET struct (i.e.
System.Drawing.Point).

It doesn't, particularly (and being a struct has nothing to do with
it). It has the same behaviour in each case - it looks in the calling
assembly and mscorlib, unless the assembly details are also provided.
In this case, System.Drawing.Point isn't in the calling assembly or
mscorlib, so it returns null, as documented. It would do the same for a
user-defined type in a different assembly.
 
M

marco_segurini

Thanks a lot Jon.
It doesn't, particularly (and being a struct has nothing to do with
it). It has the same behaviour in each case - it looks in the calling
assembly and mscorlib, unless the assembly details are also provided.
In this case, System.Drawing.Point isn't in the calling assembly or
mscorlib, so it returns null, as documented. It would do the same for a
user-defined type in a different assembly.

At the moment I am looking the MSDN examples on how to implement
strongly typed CollectionBase and DictionaryBase classes. The
OnValidate is implemented using Type.GetType:

public class Int16Collection : CollectionBase {

....

protected override void OnValidate( Object item) {
if ( item.GetType() != Type.GetType("System.Drawing.Point") )
throw new ArgumentException( "value must be of type
System.Drawing.Point", "item" );
}

}

Now I know that this in not a general method.


I have replace that member-function with this:

protected override void OnValidate( Object item )
{
if (!(item is System.Drawing.Point))
throw new ArgumentException( "item must be of type
System.Drawing.Point.", "item" );
}

that in this case works.

Is this a general method to verify the object type?

Marco.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top