Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if an object is a generic collection

We are dynamically building some SQL statements and we are utilizing the IN operator. If our value is a collection of values such that:

List<Guid> guids = new List<Guid>()

I want to be able to provider 'guids' to my clause builder, have it verify the type and if it is enumerable create a clause like:

IN ( {Guid1}, {Guid2}, {Guid3} )

Checking that the value is IEnumerable like this:

if (value is IEnumerable)

falls down when a string is passed in (which happens pretty regularly :) ). What is the best way to validate this type of condition?

like image 783
Adam Driscoll Avatar asked Mar 05 '10 16:03

Adam Driscoll


People also ask

How do you know if a type is generic?

To examine a generic type and its type parametersGet an instance of Type that represents the generic type. In the following code, the type is obtained using the C# typeof operator ( GetType in Visual Basic, typeid in Visual C++). See the Type class topic for other ways to get a Type object.

What is a generic type in C#?

Generic means the general form, not specific. In C#, generic means not specific to a particular data type. C# allows you to define generic classes, interfaces, abstract classes, fields, methods, static methods, properties, events, delegates, and operators using the type parameter and without the specific data type.

Where is generic type constraint?

The where clause in a generic definition specifies constraints on the types that are used as arguments for type parameters in a generic type, method, delegate, or local function. Constraints can specify interfaces, base classes, or require a generic type to be a reference, value, or unmanaged type.

What is the benefit of having a generic collection?

Better performance. Generic collection types generally perform better for storing and manipulating value types because there is no need to box the value types. Generic delegates enable type-safe callbacks without the need to create multiple delegate classes.


3 Answers

How about:

if(value .GetType().IsGenericType && value is IEnumerable)
like image 157
Vivek Avatar answered Sep 29 '22 04:09

Vivek


You could try value.GetType().IsGenericType in combination with your check for IEnumerable.

like image 42
Nick Avatar answered Sep 29 '22 03:09

Nick


What about :

value is IEnumerable<Guid>

It's better if you expect Guid instances, isn't it ?

like image 25
Seb Avatar answered Sep 29 '22 02:09

Seb