User999999
User999999

Reputation: 2520

Cast typed Ilist(Interface) to typed Array

I currently have an IList which is being constructed as followed:

var baseType = typeof(List<>);
Type genericType = baseType.MakeGenericType(prop.PropertyType.GetGenericArguments().First());
IList returnedvalues = (IList)Activator.CreateInstance(genericType);

Where proprefers to a property of an Object. For example

public List<String> PersonNames{get; set;}

or

public List<SomeSelfCreatedObject> MyObjects{get; set;}

Now the customers wants me to return this Ilist as an Array. I know how to return it as an Object[] or any other predefined type(like Int,String). But is it possible to return as Array of the type defined in the code above?

so I would have the following output (after cast)

public List<SomeSelfCreatedObject> MyObjects{get; set;} 
             Would result in => SomeSelfCreatedObject[]
public List<String> PersonNames{get; set;} 
             Would result in => String[]

Upvotes: 0

Views: 151

Answers (2)

Chris
Chris

Reputation: 27609

The type returned by Activator.CreateInstance(genericType) is of the type List<T> where T is unknown at compile time. This makes casting tricky. We can use dynamic here and the direct call to Enumerable.ToArray() to get the value as T[].

dynamic returnedvalues = Activator.CreateInstance(genericType);
dynamic valuesAsArray = Enumerable.ToArray(returnedvalues);

We still can't know the type of valuesAsArray at compile time which makes it tricky to use but I don't know if this will be a problem for you or not. It depends on what you want to do with it next...

As Sriram Sakthivel points out in comments you can cast valuesAsArray to something non-dynamic. It can never be a generic type because you don't know the compiletime type but you could cast to Array or any number of other things (see What interfaces do all arrays implement in C#? for info on what else you could cast it to).

Upvotes: 3

Nick Cipollina
Nick Cipollina

Reputation: 551

Unless I am misunderstanding your question, can't you just call the ToArray() method on your List?

Upvotes: 2

Related Questions