❔ help with self referential class typing
I was trying to make a node class I can inherit from and ran into a ton of trouble,
in my original solution the "next" value was still a node rather then the child class, I looked around and people were saying to use a self referential generic class signature so I used this:
and started writing, I even got some inheritance to work,
however I ran into a few problems in some of the functions:
in this function for example, how can I make a new "Self" object? as I do not know what constructors it has. and if I try to build a node I cant set it as next as I expect a Self
object, am I missing a trick to get this to work?
6 Replies
var self = (Self)Activator.CreateInstance(typeof(Self), item);
ah so I can go to the constructors of Self as a function argument, ty
it works ty 🙂
you can use the
new()
generic type constraint which would allow you to instantiate the type but require it to define a parameterless constructor
what benefits is inheritance giving you here? if it's just to add a couple fields it doesn't seem worth itI do need to use constructors tho so I cant just have an empty use
I cut out some parts of the code as they were irrelevant
I have some methods like splice and stuff
You can have static members on interfaces now. One idea is to use such a static method as a 'named ctor'. You can then constrain Self to implement that interface
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.