Home

Linqpad Cannot find Local Type for reflection.

I am using Linqpad 6 and I have the following code.

void Main()
{
var assembly = Assembly.GetAssembly(typeof(Bear));//.GetTypes().Dump();;

Console.WriteLine("What do you want");
var animal = (IAnimal)(Activator.CreateInstance(assembly.FullName,Console.ReadLine()).Unwrap());
animal.Greetings().Dump();

}

interface IAnimal
{
string Greetings();
}

public class Bear : IAnimal
{
public string Greetings()
{
return "I am a bear";
}
}

When the user would type in "Bear" Linqpad throws an TypeLoadException "Could not load type 'Bear' from assembly 'LINQPadQuery, Version=1.0.0.525, Culture=neutral, PublicKeyToken=null'

Why is that?

Comments

  • Sorry for the formatting, cant edit it.

  • LINQPad wraps your code in a class called UserQuery, so the type name is "UserQuery+Bear". (This enables some useful features, such as being able to access static members without qualification.)

    You can disable this wrapping with the #LINQPad nonest directive, so the type name is just "Bear"

    #LINQPad nonest
    void Main()
    {
        var assembly = Assembly.GetAssembly (typeof (Bear));//.GetTypes().Dump();;
        typeof (Bear).FullName.Dump();
    
        Console.WriteLine ("What do you want"); 
        var animal = (IAnimal)(Activator.CreateInstance (assembly.FullName, Console.ReadLine()).Unwrap());
        animal.Greetings().Dump();
    }
    
    interface IAnimal
    {
        string Greetings();
    }
    
    public class Bear : IAnimal
    {
        public string Greetings()
        {
            return "I am a bear";
        }
    }
    

    Note that you can improve the activation by avoiding the unnecessary assembly resolution:

    var animal = (IAnimal) Activator.CreateInstance (assembly.GetType (Console.ReadLine()));

  • edited February 2023

    @JoeAlbahari said:

    You can disable this wrapping with the #LINQPad nonest directive, so the type name is just "Bear"

    I am sorry to bother you , but I posted a very simillar question (a couple of posts before this one) and tried to add #LINQPad nonest , but nothing happens. It would be very kind of you to help me too. Thank you in advance.

Sign In or Register to comment.