Alex Krupka
Alex Krupka

Reputation: 730

Using reflection to cast a object

I'm a little new to reflection so forgive me if this is a more basic question I'm writing a program in c# and am trying to write a generic Empty or null checker method so far the code reads as

 public static class EmptyNull
    {
       public static bool EmptyNullChecker(Object o)
       {
           try
           {
               var ob = (object[]) o;
               if (ob == null || !ob.Any())
                   return true;
           }
           catch (Exception e)// i could use genercs to figure out if this a array but                  //figured i just catch the exception
           {Console.WriteLine(e);}
           try
           {
               if (o.GetType().GetGenericTypeDefinition().Equals("System.Collections.Generic.List`1[T]"))
               //the following line is where the code goes haywire
              var ob = (List<o.GetType().GetGenericArguments()[0].ReflectedType>)o;
               if (ob == null || !ob.Any())
                   return true;
           }
           catch (Exception e)
           { Console.WriteLine(e); }
           return o == null || o.ToString().Equals("");//the only thing that can return "" after a toString() is a string that ="", if its null will return objects placeMarker
       }
    }

now obviously the for a list i need a way to figure out what type of generic list it is so i want to use reflection to figure it out and then cast it with that reflection is this possible

Thank You

Upvotes: 0

Views: 462

Answers (3)

FishBasketGordo
FishBasketGordo

Reputation: 23122

If all you want is a single method that returns true if an object is null or if the object is an empty enumerable, I wouldn't use reflection for that. How about a couple of extension methods? I think it would be cleaner:

public static class Extensions
{
    public static bool IsNullOrEmpty(this object obj)
    {
        return obj == null;
    }

    public static bool IsNullOrEmpty<T>(this IEnumerable<T> obj)
    {
        return obj == null || !obj.Any();
    }
}

Upvotes: 9

Reed Copsey
Reed Copsey

Reputation: 564333

If you're using .NET 4, you can take IEnumerable<out T>'s new support for covariance into account, and write this as:

public static bool EmptyNullChecker(Object o)
{
    IEnumerable<object> asCollection = o as IEnumerable<object>;
    return o != null && asCollection != null && !asCollection.Any(); 
}

I would, however, suggest a better name such as one inspired by string.IsNullOrEmpty

Upvotes: 3

Related Questions