user1374495
user1374495

Reputation: 33

Add Item into a generic List in C#

I tried to insert an object into a generic BindingList. But if I try to add a specific object the compiler says: "Argument type ... is not assignable to parameter type"

private void JoinLeaveItem<T>(BindingList<T> collection)
    {

        if (collection.GetType().GetGenericArguments()[0] == typeof(UserInformation))
        {
            var tmp = new UserInformation();
            collection.Add(tmp);
        }
    }

Please help me

Upvotes: 2

Views: 7761

Answers (2)

vidstige
vidstige

Reputation: 13079

You cannot have objects of two different types that does not have a common anscestor in a strongly typed list. That is: In your case you will need to different collections unless your two (or more) classes have a common base class.

Try creating overloads instead, like this

private void JoinLeaveItem(BindingList<UserInformation> collection)
{
    collection.Add(new UserInformation());
}

private void JoinLeaveItem(BindingList<GroupInformation> collection)
{
    collection.Add(new GroupInformation());
}

Use it like this

JoinLeaveItem(userInformationCollection)
JoinLeaveItem(groupInformationCollection)

Note: I've inlined the tmp variable.

Upvotes: 1

Bob Vale
Bob Vale

Reputation: 18474

From what you've described in your comments do you want to do something like this....

private void JoinLeaveItem<T>(BindingList<T> collection)  where T: new()
    { 
            var tmp = new T(); 
            collection.Add(tmp); 
    } 

EDIT If you want to add extra Tests to limit to only the items you specify you could add a big test at the beginning

private void JoinLeaveItem<T>(BindingList<T> collection)  where T: new()
    { 
        if (typeof(T) == typeof(UserInformation) || typeof(T) == typeof(GroupInformation) 
            var tmp = new T(); 
            collection.Add(tmp); 
        } 
    } 

Alternatively you can make a more generic solution via use of an interface.

Define an interface

public interface ILeaveItem { }

Make UserInformation and GroupInformation inherit from it and then use

private void JoinLeaveItem<T>(BindingList<T> collection)  where T: ILeaveItem, new()
    { 
            var tmp = new T(); 
            collection.Add(tmp); 
    } 

Upvotes: 0

Related Questions