Home > front end >  How to read class Properties without instantiation?
How to read class Properties without instantiation?

Time:12-02

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 dynamically, stored as a string in a variable.

(As classes are added independentely of the developer of the function above, the code of the function won't be extended by "switch-case" for every new Class)

Unfortunately, the following Code...

// first part ist just to explan and won't be available in the code... the content of modelClass will unknown
MyModel mod = new();
string modelClass = mod.GetType().ToString();
//
Console.WriteLine("Class of Model is: {0}", modelClass );
PropertyInfo[] myPropertyInfo;
myPropertyInfo = Type.GetType(modelClass).GetProperties();

throws an ...

fail: Microsoft.AspNetCore.Components.Server.Circuits.CircuitHost[111]
      Unhandled exception in circuit 'Vir-nbPwhGHcOpSjnVvTlz4-11RtlEirY2qypkNIPw8'.
      System.NullReferenceException: Object reference not set to an instance of an object.

The Console Output confirms, the right Class has been used. But i am confused, as i thought GetProperties() doesn't need an concrete Object.


Using the Object directly, works without problem

myPropertyInfo = mod.GetType().GetProperties();

Also typeof() seems close to what i'm looking for. But it looks as i can't pass a Variable which contains the String of the desired Class. Then, typeof() determines the type of the Variable i pass

CodePudding user response:

I would bet that Type.GetType(modelClass) returns null. If we look in the documentation we find this description of the return value:

The type with the specified name, if found; otherwise, null.

So we know modelClass does not contain a valid type name.

This becomes even more clear when we look at modelClass = mod.GetType().ToString();. .ToString() converts the object to a string, it does not return the name of the type. If you want the name of the type, use mod.GetType().FullName

I would suggest reading eric lipperts article on how to debug small programs. Because this should be fairly easy to debug by just placing a breakpoint and checking variables.

CodePudding user response:

Your problem is that Type.ToString() just returns the types (short) name without qualifiers. So in your case just "MyModel". 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.

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

  • Related