Check if the typeof(object) in a List is a reference type

4.2k views Asked by At

this seems odd to me:

if(customerList.Count > 0)
{
   if(typeof(customerList[0]).IsReferenceType)
   {
      // do what I want
   }
}

How would you do it?

4

There are 4 answers

1
herzmeister On
bool isReferenceType = !(customerList[0] is ValueType);

EDIT

Or are you looking for something like:

bool listIsOfReferenceTypeObjects = !myList.GetType().GetGenericArguments()[0].IsValueType;
3
Timwi On
  1. To determine whether the first item in a list is an object of a reference type:

    bool isReferenceType = !(customerList[0] is ValueType);
    
  2. To determine whether a list is a List<T> for some T that is a reference type:

    var listType = customerList.GetType();
    if (!listType.IsGeneric || listType.GetGenericTypeDefinition() != typeof(List<>))
        // It’s not a List<T>
        return null;
    return !listType.GetGenericArguments()[0].IsValueType;
    
1
Adesit On

You are probably trying to determine the actual type of the generic parameter of a generic collection. Like determining at runtime what is a T of a particular List<T>. Do this:

Type collectionType = typeof(customerList);
Type parameterType = collectionType.GetGenericArguments()[0];
bool isReference = !parameterType.IsValueType;
4
Elisabeth On

ok that worked and I get no exception, when the customerList is empty.

Type collectionType = customerList.GetType();
   Type parameterType = collectionType.GetGenericArguments()[0];
   bool isReference = !parameterType.IsValueType;

@Adesit you get a point because your sample was right except the first line :P