Thursday, April 23, 2015

Object Casting

On my most recent homework assignment I need to create a custom media formatter to return a response from my Web API service in a specific format that is based on XML.  Although I plan to write another topic on the whole custom media formatter, this is a quick hitter to discuss how to cast a variable of type object into an IEnumerable of another type (assuming the object is actually an IEnumerable of that other type).

When you inherit from the BufferedMediaTypeFormatter class you have the option to override the WriteToStream method, which accepts a Type, object, Stream, and HttpContent.  In my case, the object could be either a single instance or a List of the same type of object (in this case it was a model named BaseViewModel).

What I needed to do was handle writing the output differently if I had a single object compared to a list of objects.  So I did this:


   1:  if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof (List<>))
   2:  {
   3:      var objectType = type.GetGenericArguments()[0];
   4:      var genericListType = typeof(List<>).MakeGenericType(objectType);
   5:      var listOfObjects = (IEnumerable)Activator.CreateInstance(genericListType);
   6:  }

Now, this isn't exactly what I did because I did always know that my object would be an instance of BaseViewModel, but this little bit of code did allow me to cast my object into a list of the underlying object of the object that was passed.  Wait, I'm not sure that last part made sense.

Basically, since a List technically inherits from object, I was able to (through those three lines) cast my object into a List.  We'll just go with that.  It works.

No comments:

Post a Comment