Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Globally alias a generic class name?

Tags:

c#

alias

in some project we are using Generics, and we get a lot of lines like this:

Line<SomeTClass,SomeCClass> myLine =
           (Line<SomeTClass,SomeCClass>)LineFactory.CreateLine(...)

We can declare local alias, with using X = Line<SomeTClass,SomeCClass>.

Then we can write, X myLine = (X)LineFactory.CreateLine(...).

We have a lot a combination of <T,C> but we often use the same. Is it possible de declare the using globally, so that we won't have to declare the alias in each file?

like image 523
Francois Avatar asked Sep 14 '25 01:09

Francois


1 Answers

No such thing as a global alias. What you can do is use type inference to simplify your declarations:

var myLine = (Line<SomeTClass, SomeCClass>)LineFactory.CreateLine(...);

and if that's not specific enough for the inference system, you can make the CreateLine() method generic to enforce it:

var myLine = LineFactory.CreateLine<Line<SomeTClass, SomeCClass>>(...);

and given the name of the LineFactory type, maybe even simplify it some more:

var myLine = LineFactory.CreateLine<SomeTClass, SomeCClass>(...);

This last option feels "right" to me in some way I can't fully articulate. Just in case you need a little help, the method declaration would look like something this:

public static class LineFactory 
{
    public static Line<T,C> CreateLine<T,C>(...) { ... }
}
like image 108
Joel Coehoorn Avatar answered Sep 16 '25 15:09

Joel Coehoorn