Home > Software engineering >  Setting <T> in multiple generic classes in one location during compile time
Setting <T> in multiple generic classes in one location during compile time

Time:11-22

Is it possible to set the <T> type in a generic class using the type of another class, if both are known during compile time and will not change during runtime?

For example, I have lots of 3rd party UI grids in my app. Each grid has several types of event callback args that get returned in handler methods. They all are generics and get fed the class that they are displaying.

I have numerous grids displaying different types with a lot of identical methods, and I'm trying to simplify so that my boilerplate setup can be done just by changing the desired class in one spot.

Existing Code:

Comment selectedComment; //Comment is type that is displayed in grid and all args
Grid<Comment> commentGrid;

void RowSelected(RowSelectEventArgs<Comment> args)
    {
        // Some code here
    }

Desired Code (Example non-functioning

Comment selectedComment; //Comment is type that is displayed in grid and all args

Type type = typeof(selectedComment); //I want to use some sort of line to set all <T> in one spot

Grid<type> commentGrid;  //Is it possible to refers <T> to the holder variable 'type' above?

void RowSelected(RowSelectEventArgs<type> args)
    {
        // Some code here
    }

//Both sections that say <type> give error: The type or namespace could not be found.

CodePudding user response:

You can use a using alias directive at the top of your file, which will define the type everywhere in that file.

using T = MyNamespace.Comment;
T selectedComment;

Type type = typeof(T);

Grid<T> commentGrid;

void RowSelected(RowSelectEventArgs<T> args)
{
    // Some code here
}

T is probably a bad choice, you might want something slightly more descriptive

  • Related