Home > Net >  How to define the type of TItem inside of generic class, or set class name as a variable?
How to define the type of TItem inside of generic class, or set class name as a variable?

Time:12-04

How can I create a class variable (or class alias) on top of the file and use that variable name later in the file? My goal is to reuse (copy) this class in several places and change only the class type variable on top of the file. Otherwise, every time I copy this class, I have to replace all class names in the file, which is more than a thousand lines. Sometimes you just miss some of them. Of course, not all classes have the same properties, and when I'll change the class name from Address to Employee, VS editor will highlight those parts -

"Employee does not contain member called 'StreetNo'"

Then I will take care of that red squiggly lines.

Is it possible? For example:

var model = Employee;  // Employee is a class

and below use it as follows:

model newInstance = new model();

I tried to use generics (TItem), but I cannot assign the type of TItem inside of generic class:

public class Foo<TItem> where TItem : Employee
{
    // where TItem : Employee - this part of code only sets constraint, but doesn't set TItem equal to Employee - (e.g. TItem = Employee)
}

This is a very basic example of a razor component, which in fact is a partial class. I just simplified the case. Any ideas?

CodePudding user response:

You can try using aliases:

using Model = Employee;

And later in the code:

Model newInstance = new Model();
  • Related