Search code examples
c#classactivator

Create a Model Class Name from a String


I am trying to dynamically insert an existing model class name into a declaration so I don't have to do this:

var n1 = entry.Entity as MyClassName1;
var n2 = entry.Entity as MyClassName2; 
var n3 = entry.Entity as MyClassName3; 
[n4...n200]

This is what I am trying to achieve but with the class name generated dynamically

 var n = entry.Entity as MyClassName1;

Here is how I am trying to get there, based on what I read about Activator.CreateInstance.

 //Get string representation of the class name
 var tableNameStr = entry.EntitySet.Name.TrimEnd('s');
 //Get class type
 var t = Type.GetType(tableNameStr);
 //Instantiate
 var n = entry.Entity as (Activator.CreateInstance(t));

Getting the following error:

Only assignment, call, increment, decrement and new object expressions can be used as a statement

How can I do this?

Thanks


Solution

  • It depends on what you want to do.

    var n1 = entry.Entity as MyClassName1;
    

    basically does two things:

    1. MyClassName1 n1; -- it statically types n1 as MyClassName1.

    2. n1 = (entry.Entity is MyClassName1 ? (MyClassName1)entry.Entity : null); -- it assigns null to n1, if it is not of type MyClassName1¹.


    The first thing cannot be done dynamically. A static type is known at compile time.

    The second thing can be done dynamically:

    if (GetType(typeNameAsString).IsAssignableFrom(entry.Entity.GetType()) {
        n1 = entry.Entity;
    } else {
        n1 = null;
    }
    

    ¹ ...with a few exceptions, which are probably irrelevant here.