1

i'm trying to create method that will display all methods that specific type has.
the code is:

public static void AllMethods(Type t)
    {
        var query = from x in t.GetMethods() select x;
        foreach (var item in query)
            Console.WriteLine(item.Name);
    }

i tried another version of this:

public static void AllMethods(Type t)
    {
        MethodInfo[] m = t.GetMethods();
        foreach (MethodInfo item in m)
            Console.WriteLine(item.Name);
    }

both versions compile, but when it come to pass a parameter, the NullReferenceException occurs:

static void Main(string[] args)
    {   
        AllMethods(Type.GetType("Z")); // Z is a class name

        Console.ReadLine();
    }

i guess the solution is simple, but my brain now can't figure out it)
any suggestions?

Aleksei Chepovoi
  • 3,915
  • 8
  • 39
  • 77
  • it works, when using typeof(Z),, but i'm learning reflection, so i need to use Type.GetType() – Aleksei Chepovoi Nov 23 '12 at 11:33
  • Possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Nasreddine Oct 04 '15 at 09:09

1 Answers1

3

My guess is that either Z isn't the fully-qualified class name (you need to include the namespace) or it's the name of a class which is neither in mscorlib nor the calling assembly. To use a class from another assembly, you need to include the assembly name as well (including version number etc if it's strongly-named). Or use Assembly.GetType() which is simpler, if you have a reference to the assembly already, e.g. because you know another type that is in the same assembly.

Assuming I'm right, you should ignore your AllMethods method entirely. Instead check this:

Type type = Type.GetType(...);
Console.WriteLine("type is null? {0}", type == null);

Of course, if you know the type at compile-time, you'd be better off using typeof.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194