Can I cast a generic list, or do I need another approach

R

RichB

I have an abstract class Domain which is responsible for validation of my
model. All classes in the model inherit from Domain for operations such as
bool IsValid {get;}.

I have a Person class:

public class Person :Domain
{
private string name;
private List <Address> addresses;
}

where
class Address :Domain

In order for IsValid to be true for Person, it also needs to be true for all
addresses.

I therefore within my overridden IsValid Method have a foreach loop:

bool b;
foreach (Domain o in this.addresses)
{
if (o.IsValid)
b = false;
}


This works fine, but each Address has a List<PhoneNumber> phoneNumbers where
PhoneNumber:Domain. This would use the same loop of code except: foreach
(Domain o in this.phoneNumbers).

Therefore I decided that it would be best to put this functionality into a
Method in the Domain class. Since the Address and PhoneNumber number classes
are both derived from Domain, I thought that I would be able to provide a
method something like:

public IsChildListValid(List<Domain> domainList)
{

}

However List<Address> and List<PhoneNumber> does not cast to List<Domain>.
Is there a way to do this, or are there any other options other than
repeating the code?

Thanks, Richard
 
J

Jon Skeet [C# MVP]

I have an abstract class Domain which is responsible for validation of my
model. All classes in the model inherit from Domain for operations such as
bool IsValid {get;}.

However List<Address> and List<PhoneNumber> does not cast to List<Domain>..
Is there a way to do this, or are there any other options other than
repeating the code?

Yes, there's a way to do it - you need to make the method generic:

public bool IsChildListValid<T>(List<T> domainList) where T : Domain
{
...
}

That should work with no problems.

Jon
 
R

RichB

Thanks, just what I was after.

I have an abstract class Domain which is responsible for validation of my
model. All classes in the model inherit from Domain for operations such as
bool IsValid {get;}.

However List<Address> and List<PhoneNumber> does not cast to List<Domain>.
Is there a way to do this, or are there any other options other than
repeating the code?

Yes, there's a way to do it - you need to make the method generic:

public bool IsChildListValid<T>(List<T> domainList) where T : Domain
{
...
}

That should work with no problems.

Jon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top