user3308043
user3308043

Reputation: 827

Namespace causes NullReferenceException?

I have the following program, which is a sampling piece of code that shows how C# reflection operates on a class. Everything works fine, no problems at all.

public class Program
{

public static void Main()
{

    Type T = Type.GetType("Customer");
    Console.WriteLine("Information about the Type object: ");
    Console.WriteLine(T.Name);
    Console.WriteLine(T.FullName);
    Console.WriteLine();

    Console.WriteLine("Property info:");
    PropertyInfo[] myPropertyInfoArray = T.GetProperties();

    foreach(PropertyInfo myProperty in myPropertyInfoArray)
    {
        Console.WriteLine(myProperty.PropertyType.Name);
    }
    Console.WriteLine();

    Console.WriteLine("Methods in Customer:");
    MethodInfo[] myMethodInfoArray = T.GetMethods();

    foreach(MethodInfo myMethod in myMethodInfoArray)
    {
        Console.WriteLine(myMethod.Name);
    }


    Console.ReadKey();
}

}


class Customer
{

public int ID {get;set;}
public string Name {get;set;}

public Customer()
{
    this.ID = -1;
    this.Name = string.Empty;
}

public Customer(int ID, string Name)
{
    this.ID = ID;
    this.Name = Name;
}

public void PrintID()
{
    Console.WriteLine("ID: {0}", this.ID);
}

public void PrintName()
{
    Console.WriteLine("Name: {0}", this.Name);
}

}

The problem that I'm experiencing is that when I wrap all of the code in a Namespace, I suddently get a NullReferenceException on the Type object. Why could this be?

Upvotes: 0

Views: 146

Answers (1)

Dave Bush
Dave Bush

Reputation: 2402

Because it no longer knows where Customer is. You'll need

Type T = Type.GetType("NameSpaceName.Customer");

Upvotes: 4

Related Questions