Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Object to List<string> in c#?

I have a List<string> in Model. When I write a html helper, I can get the data from metadata.Model, which is an object

// this is from MVC3 (namespace System.Web.Mvc -> ModelMetadata), I did not write this
// Summary:
//     Gets the value of the model.
//
// Returns:
//     The value of the model. For more information about System.Web.Mvc.ModelMetadata,
//     see the entry ASP.NET MVC 2 Templates, Part 2: ModelMetadata on Brad Wilson's
//     blog
public object Model { get; set; }

My question is: how to get List<string> from an Object?

like image 643
Eric Yin Avatar asked Jan 28 '12 07:01

Eric Yin


1 Answers

If the underlying type of the object variable is List<string>, a simple cast will do:

// throws exception if Model is not of type List<string>
List<string> myModel = (List<string>)Model; 

or

// return null if Model is not of type List<string>
List<string> myModel = Model as List<string>;
like image 51
Kyle Trauberman Avatar answered Oct 08 '22 20:10

Kyle Trauberman