Generics and Lists

I have 3 classes, 1 class is a parent class (Account) and the other two are child classes (Cheque and Savings). How do I create a method in a GenericList Class to display all information from a parent class (i.e. FullName, AccountNumber) instead of using two different list collection classes?

This is what I have so far...

public class GenericListOperations<T>
{
    // This is the code to reverse the list but it doesnt work
    public List<T> Generic_Reverse_list(List<T> e)
    {
        List<T> b = new List<T>();
        return b;
    }
}

Upvotes: 0

Views: 51

Answers (2)

Paarth
Paarth

Reputation: 10397

Based on your question I believe you're trying to get at the common properties of the Cheque and Savings class that they've inherited from the Account class.

In this case you can achieve that by modifying your class definition to:

public class GenericListOperations<T> where T : Account

You can also apply that to functions individually if you wish.

Upvotes: 1

sameerfair
sameerfair

Reputation: 426

From what I understand from your question, you want an explicit way of returning a List of Accounts whether Account be a Cheque or Savings. If that is correct, you can just contrain the Type T to

where T : Account

or specifically

public class GenericListOperations<T> where T : Account

This is for your reference.

https://msdn.microsoft.com/en-us/library/d5x73970.aspx

Not only that but you can also just return a List of Account instead of a generic

Upvotes: 1

Related Questions