Reputation: 13436
Suppose I have classes set up like this:
public abstract class GenericCustomerInformation
{
//abstract methods declared here
}
public class Emails : GenericCustomerInformation
{
//some new stuff, and also overriding methods from GenericCustomerInformation
}
public class PhoneNumber : GenericCustomerInformation
{
//some new stuff, and also overriding methods from GenericCustomerInformation
}
//and more derivative classes for emails, addresses, etc ..
Then I have this function to return a specific list:
public List<GenericCustomerInformation> GetLists<T>()
{
if (typeof(T) == typeof(Alias))
{
return aliases.Cast<GenericCustomerInformation>().ToList();
}
if (typeof(T) == typeof(PhoneNumber))
{
return phoneNumbers.Cast<GenericCustomerInformation>().ToList();
}
// .. and the same for emails, addresses, etc ..
}
Now suppose I want to add to these lists using just one function:
public void AddToList<T>(T iGenericCustomerInformation)
{
GetLists<T>().Add((T)(object)iGenericCustomerInformation); //Doesn't work as intended. GetLists<T> seems to be returning lists as value, which is why any additions
}
The problem is that AddToList<T>
doesn't work as intended. GetLists<T>
seems to be returning lists as value, which is why any additions I do are not reflected in the primary list structure ...
So how to return the list as a reference, so that I can use that reference to do list additions through other functions ?
Upvotes: 0
Views: 615
Reputation: 998
Why not keep all your lists in a dictionary of lists ?
private Dictionary<Type, List<GenericCustomerInformation>> MyLists;
public List<GenericCustomerInformation> GetLists<T>()
{
return MyLists[typeof(T)];
}
public void AddToLists<T>(GenericCustomerInformation item)
{
GetLists<T>().Add(item);
}
Upvotes: 0
Reputation: 101758
You're already defeating the point of generics by having all those typeof()
s and if
statements. That's not generic at all. I'd say just put the if
statement in your AddToList()
method and nix the generics.
public void AddToList(GenericCustomerInformation item)
{
Alias aliasItem = item as Alias;
if(aliasItem != null)
{
aliases.Add(aliasItem);
return;
}
PhoneNumber phoneNumberItem = item as PhoneNumber;
if(phoneNumberItem != null)
{
phoneNumbers.Add(phoneNumberItem);
}
}
Upvotes: 1