Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't GetType() find types when invoked through a method group delegate? [duplicate]

Tags:

c#

reflection

People also ask

What is return type of GetType ()?

The C# GetType() method is used to get type of current object. It returns the instance of Type class which is used for reflection.

What is the difference between GetType and typeof in C#?

typeof keyword takes the Type itself as an argument and returns the underline Type of the argument whereas GetType() can only be invoked on the instance of the type.

How do I use GetType?

The GetType method is inherited by all types that derive from Object. This means that, in addition to using your own language's comparison keyword, you can use the GetType method to determine the type of a particular object, as the following example shows.

What is GetType?

GetType Method is used to find the type of the current instance. This method returns the instances of the Type class that are used for consideration. Syntax: public Type GetType (); Return Value: This method return the exact runtime type of the current instance.


This is really interesting. It's a mixture of the behaviour of Type.GetType(string) in terms of the calling assembly, and how method group conversions work.

First, the Type.GetType documentation includes this:

If typeName includes the namespace but not the assembly name, this method searches only the calling object's assembly and Mscorlib.dll, in that order.

In your first call, you're passing in a delegate which calls Type.GetType... but it isn't particularly called from your assembly. It's effectively called directly from the Select method in LINQ... if you looked at the stack trace from within Type.GetType, you'd see Select as the direct caller, I believe.

In your second call, you're passing in a closure which calls Type.GetType, and that call is within your assembly.

That's why it finds the type in the second case but not the first. This is further validated by specifying a type which is in the LINQ assembly:

var fullName = typeof(Enumerable).FullName;

Then the results are the opposite way round:

Full name: System.Linq.Enumerable
Method group: 'System.Linq.Enumerable'
Closure: ''

If you specify something in mscorlib (e.g. typeof(string).FullName) then both approaches work:

Full name: System.String
Method group: 'System.String'
Closure: 'System.String'

The way to get around this oddity when looking for your class, still using a method group, is simply to supply the assembly-qualified name instead:

var fullName = typeof(TestClass).AssemblyQualifiedName;