0

How can i read all class Properties, without having an instantiated object of this Class nor hard-coding the name of the class itself? The name of the class is stored in a string-variable.

string className = "myNamespace.myClass";
PropertyInfo[] myPropertyInfo;
try
{
    myPropertyInfo = Type.GetType(className).GetProperties();
} catch(Exception ex)
{
    Console.WriteLine(ex.ToString());
}

always returns a

System.NullReferenceException: Object reference not set to an instance of an object.

I'd like avoiding a solution like

switch(className) {
   case "myNamespace.myClass":
      myNamespace.myClass obj = new();
      break;
   case "myNamespace.anotherClass":
      myNamespace.anotherClass obj = new();
      break;
   case "anotherNamespace.myClass":
      anotherNamespace.myClass obj = new();
      break;
}
myPropertyInfo = obj.GetType().GetProperties();

Besi
  • 5
  • 3

1 Answers1

1

Your problem is that Type.ToString() just returns the types (short) name without qualifiers. So in your case just "MyModel" instead of "MyNamespace.MyModel, MyAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null". However Type.GetType() needs an assembly-qualfied name. Otherwise it just returns null because the type wans't found. From the docs for the string-parameter for Type.GetType:

The assembly-qualified name of the type to get. See AssemblyQualifiedName. If the type is in the currently executing assembly or in mscorlib.dll/System.Private.CoreLib.dll, it is sufficient to supply the type name qualified by its namespace.

Instead of using mod.GetType.ToString() you should use mod.GetType.AssemblyQualifiedName.

When on the other hand you already have a concrete instance of your model-class and call GetType on that, you never get null, as every object has a type.

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
  • Hi, thank you. And what if the Object 'mod' isn't available, but a variable containing namespace and class Name, e.g. String classname = "my.namespace.myModel"; I guess my first example above is confusing. – Besi Dec 02 '22 at 23:30
  • Hi @MakePeaceGreatAgain, i just rewrote my question. Maybe this helps to precise the problem – Besi Dec 09 '22 at 09:05
  • @Besi you need to provide an assembly-qualified named as mentioned in the docs for `Type.GetType`. This is a string containing the namespace, the type-name, the assembly, it's version and it's culture – MakePeaceGreatAgain Dec 09 '22 at 09:28