I've this base class that contains list of other classes
public class Blacklist
{
public int Id { get; set; }
public virtual IEnumerable<Card> Cards { get; set; }
}
Where Card class looks like
public class Card
{
public int Id { get; set; }
public string Cuid { get; set; }
public int BlacklistId { get; set; }
}
Then I have implemented a derived class that extends Blacklist class
public class BlacklistTwo : Blacklist
{
public new IEnumerable<CardTwo> Cards { get; set; }
}
where CardTwo class extends the base Card class
The problem occurs when I try to invoke a method that accept the base class as parameter with the derived instance. The type of outer class is alright but type of cards stays implemented as base class .
Example:
Insert(
new BlacklistTwo(){
Id = 1,
Cards = new List<CardsTwo>()
{ new CardTwo() { Id = 123123, Cuid = "123213", BlacklistId = 1}});
public void Insert(Blacklist blacklist)
{
blacklist.GetType(); // returns BlacklistTwo
blacklist.Cards.GetType(); // returns IEnumerable<Card> insted of IEnumerable<CardTwo>
}
It works when I set the parameter of method to dynamic but I would like to avoid it if possible.
CodePudding user response:
As pointed out in comments - you don't actually override the property since you use the 'new' keyword. I think this may be what you are trying to achive:
public interface ICard
{
int CardId { get; set; }
string Cuid { get; set; }
int BlacklistId { get; set; }
//.. Other methods and properties
}
public class Card : ICard
{
public int CardId { get; set; }
public string Cuid { get; set; }
public int BlacklistId { get; set; }
}
public class CardTwo : ICard
{
public int CardId { get; set; }
public string Cuid { get; set; }
public int BlacklistId { get; set; }
}
public class Blacklist
{
public int Id { get; set; }
public virtual IEnumerable<ICard> Cards { get; set; }
}
public class BlacklistTwo : Blacklist
{
public override IEnumerable<ICard> Cards { get; set; }
}
And then:
public Test()
{
ICard card1 = new Card();
card1.CardId = 123123;
card1.Cuid = "123213";
card1.BlacklistId = 1;
ICard card2 = new CardTwo();
card2.CardId = 123123;
card2.Cuid = "123213";
card2.BlacklistId = 1;
Insert(new BlacklistTwo()
{
Id = 1,
Cards = new List<ICard>() { card1 ,card2 }
});
if (card1 is Card c1)
{
//Yes - this is a type of Card
}
if (card2 is CardTwo c2)
{
//Yes - this is a type of CardTwo
}
}
You could use an interface or an abstract class, and and probably even avoid extending the blacklist class