Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

this seems odd to me:

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

How would you do it?

like image 643
Elisabeth Avatar asked Dec 05 '25 20:12

Elisabeth


2 Answers

  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;
    
like image 65
Timwi Avatar answered Dec 08 '25 10:12

Timwi


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;
like image 29
Adesit Avatar answered Dec 08 '25 12:12

Adesit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!