1

If I have a generic base class

class Base<T> { }

and I derive from it

class Derived : Base<SomeReallyLongConcreteTypeName> 
{
    // Can I use the type name T here rather than SomeReallyLongConcreteTypeName
} 

is it possible to use the base type generic type parameter name in the body of the derived class? In C++ I can add

using X = T;

into the base type and use X in the derived class but I don't think type aliases can do this in C# so is there another way?

goneskiing
  • 1,659
  • 1
  • 13
  • 22
  • 4
    You can write `using T = SomeReallyLongConcreteTypeName;` in your derived class, if you want... – Jon Skeet Jun 24 '19 at 15:03
  • If you use an alias like `T` you're saving keystrokes at the expense of the time spent reading the code later. You can use autocomplete to type the class name. But even if someone reading it takes a few seconds to see what `T` means, that's extra time. Then they have to remember it - every time they see `T` - oh, right, `T` is an alias for `SomeReallyLongConcreteTypeName`. *Maybe* an alias could help, but in this case I don't see the benefit. – Scott Hannen Jun 24 '19 at 15:12
  • Jon Skeet when you say "in your derived class" I had tried adding a using like that into Derived and got an error "A using clause must precede all other elements defined in the namespace except extern alias declarations" – goneskiing Jun 24 '19 at 15:28
  • Scott Hannen you comment is an opinion on how to write code held be you but not me. – goneskiing Jun 24 '19 at 15:30
  • This question was marked as a duplicate of another, it is not, that question does not even mention generics, the topic is related but not the same. – goneskiing Jun 24 '19 at 15:33
  • So it sounds like you've put your using directive too late into the code - move it higher. Without seeing what you've tried to do, it's hard to comment further. (I do agree with Scott here though - I think this will harm readability.) – Jon Skeet Jun 24 '19 at 15:37
  • The generics are irrelevant here - the duplicate *is* a duplicate, it's just that you *happen* to be using the long type name as a type argument. – Jon Skeet Jun 24 '19 at 15:37
  • @goneskiing - You're right. You asked a literal "is it possible" question, not for my opinion. That's fair. I'm going to say that it's technically not possible. You can do `using T = SomeReallyLongConcreteTypeName` and it will match by coincidence. But if you go back to the generic class and change `T` to something else, now the alias in your derived class will no longer match the generic argument name in your generic class. So you're not really using the generic argument name, you're using another name which *happens* to be the same. – Scott Hannen Jun 24 '19 at 17:50

0 Answers0