KDecker
KDecker

Reputation: 7128

Confirm that a list of object are of the given types?

I have been going back and forth trying to determine if there is a way to determine if the objects in a List<> are of a specific type.

Basically I am trying to develop a function

public List<Object> ReadWriteArgs { get; set; }
public Booolean ConfirmRWArgs(int count, List<Type> types)
{
    if(ReadWriteArgs != null && ReadWriteArgs.Count == count)
    {
        // Compare List<Type> to the types of List<Object>
        return true;
    }
    return false;
}

But from everything I have read and everything I have tried I have come to the conclusion that this is impossible in C#.

EDIT: I want to make the comparison that I am trying to make below

public Booolean ConfirmRWArgs(int count, List<Type> types)
{
    if(ReadWriteArgs != null && ReadWriteArgs.Count == count)
    {
        if(ReadWriteArgs.Count == types.Count)
        {
            for (int i = 0; i < ReadWriteArgs.Count; i++)
            {
                // Compare the types of the objects in the list ReadWriteArgs
                // to the Types lists in the list types
                //if(ReadWriteArgs[i] is types[i])
                //if(typeof(ReadWriteArgs[i])) == types[i])
            }
            return true;
        }
    }
    return false;
}

Upvotes: 0

Views: 59

Answers (3)

Brian Gradin
Brian Gradin

Reputation: 2275

public List<Object> ReadWriteArgs { get; set; }
public bool ConfirmRWArgs(List<Type> types)
{
    for (int i = 0; i < types.Count; i++)
    {
        if (ReadWriteArgs[i].GetType() != types[i])
            return false;
    }

    return true;
}

Upvotes: 2

Jashaszun
Jashaszun

Reputation: 9270

public List<Object> ReadWriteArgs { get; set; }
public bool ConfirmRWArgs(int count, List<Type> types)
{
    return ReadWriteArgs != null
           && ReadWriteArgs.Count == count
           && ReadWriteArgs.Zip(types, (arg, type) => arg.GetType() == type).All(b => b);
}

It just zips the argument list and the type list together, checking that each argument is of the appropriate type.

To test:

ReadWriteArgs = new List<object>() { "string", 0, 'c' };
ConfirmRWArgs(3, new List<Type>() { typeof(string), typeof(int), typeof(char) }); // true
ConfirmRWArgs(3, new List<Type>() { typeof(string), typeof(int), typeof(bool) }); // false

Upvotes: 4

Coding Duchess
Coding Duchess

Reputation: 6909

something like this?

public List<Object> ReadWriteArgs { get; set; }
public Booolean ConfirmRWArgs(int count, List<Type> types)
{
    if(ReadWriteArgs != null && ReadWriteArgs.Count == count)
    {
        // Compare List<Type> to the types of List<Object>
    if (types.IsGenericType && types.GetGenericTypeDefinition() == typeof(List<>))
        return true;
    }
    return false;
}

Upvotes: 0

Related Questions