So I have a class with a wrapper class inside like so:
public class RandomClass<TK, TV>
{
internal class RandomClassWrapper<TK, TV> : RandomClass<TK, TV> {}
}
Now the reason for this is, that RandomClassWrapper is using the new keyword, to override the behaviour of some of the methods in RandomClass. This is because I only want my library to be able to access these functions.
It also needs to modify some of the private variables in RandomClass, which is why it is nested.
However, When I want to initialize this, I have to go
var rc = new RandomClass<int, int>.RandomClassWrapper<int, int>();
Why is that first <int, int> required? Why couldn’t it just be wrote like this:
var rc = new RandomClass.RandomClassWrapper<int, int>();
Is there any way that I can avoid having to type that extra <int, int> which can turn into things like: <Dictionary<string, nameofclass>, List<thisistoolong>>
That is an exaggeration, but you understand what I mean. Having to put those types twice is a huge waste of space.
Can anyone suggest a different approach?
Since this helps to clear up the question a bit, I’ll bring attention to these two comments:
So, is your question "why can’t the compiler infer the generic arguments to RandomClassWrapper from the arguments to RandomClass? – Ed S. 3 mins ago
@EdS. That is one component of the question, yes. The other, is: Since it can’t, is there an alternate approach / hack that can clean this up and avoid having to type the generic arguments twice. – caesay just now
The second class is nested within the outer generic class, so there’s no need for the type respecification.
Should compile correctly, then you just need to specify one set of generics, as the nested class automatically shares the types:
What you need to realize is that under the hood, new class definitions are generated by the compiler for each different set of generic types (poor wording, I think). This means that
RandomClass<int, int>is already a different definition toRandomClass<string, string>and thus its internal nested class is also already contained within a seperate generic definition.