C
C#16mo ago
Mmd

❔ giving current class type to a generic class

Hello the description seems to be not long as i need to write the whole thing so i'll describe the whole thing here. I have a class called Spell which is a generic class and only accepts a class with type of Legend. but now i have another class which is called TestLegend and is based on Legend. i also do have another class which is TestSpell and it generic type is TestLegend. So now i want to create a Spell array which can have any kind of Legend in itself. but heres the thing that i have to enter a type of Legend before creating an array due to the Spells' generic type and if i enter Spell<Legend>[] i cannot enter TestSpell because the array must only contain Spell with generic type of <Legend> what should i do?
6 Replies
Mmd
MmdOP16mo ago
public abstract class Spell<T> where T : Legend.Legend
public abstract class Spell<T> where T : Legend.Legend
this is Spell class
public class TestSpell : Spell<TestLegend>
public class TestSpell : Spell<TestLegend>
and this is TestSpell class what im trying to do is
new Spell<Legend>[]{new TestSpell()}
new Spell<Legend>[]{new TestSpell()}
which throws an error
Pobiega
Pobiega16mo ago
Yeah, afaik this won't work with an abstract class for Spell. You need covariance to make this work, and thats only available on an interface ie public interface ISpell<out T> where T : Legend
Mmd
MmdOP16mo ago
damn so how can i use non static fields in that class and thanks
Pobiega
Pobiega16mo ago
you can't. You should rethink the design entirely, imho
Mmd
MmdOP16mo ago
hmm aight thanks
Accord
Accord16mo ago
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.
Want results from more Discord servers?
Add your server