- Home /
Problem with type casting?
The following is my extension method to cast types
public static T Cast<T>(this object obj)
{
return (T)obj;
}
This is my extension to convert list to array:
public static List<Transform> ToTransformList(this List<WaypointData> waypointsDataList)
{
List<Transform> waypoints = new List<Transform>();
foreach(WaypointData wd in waypointsDataList)
{
waypoints.Add(wd.waypoint);
}
return waypoints;
}
I use reflection and in that if i find any filled info of type list i need to convert it to array. The filed info
FieldInfo[] fieldinfos = kamal.GetType ().GetFields();
foreach(FieldInfo field in fieldinfos)
try{
if(field.FieldType.GetGenericTypeDefinition()==typeof(List<>))
{
//kamal actual type of List<String>//
var cast = field.GetValue(kamal);
//here i need to make the program understand that this is some kind of list. Only then i can use my ToArray extension method. But the following is not working.
var array = cast.Cast<cast.GetType()>().ToArray();
}
}
catch{}
If you don't $$anonymous$$d, please clarify what the problem is and your errors in cleartext outside of the code format.
var array = cast.Cast().ToArray();
in the above line i cannot pass the type i want to cast to using get type method. It give me the following error.
Assets/DataContainer.cs(39,71): error CS1525: Unexpected symbol `)'
I need to type cast generically. How to do it?
Thanks.
Why did you write a method that converts an to a list? - There's already a ToList
method in Enumerable
(just add using System.Linq
)
You are right i simply did. I can use the one in System.Linq the only prolem i'm having here is with type casting.
@kannan21 it seems to me you want to cast your kamal
string list to an array? you can simply do this by (it should work):
var list = field.GetValue(kamal) as IEnumerable;
var array = list.ToArray(); // not your ToArray, but the one in System.Linq
Your answer
![](https://koobas.hobune.stream/wayback/20220613153856im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How can I use a variable with getcomponent<>()? 2 Answers
Make compiler treat an object variable as if it was of type X 2 Answers
GameObject.Find() type casting question 1 Answer
A smarter Way to get the Type of SerializedProperty 6 Answers
I need an Array of System.type[] from all of my ScriptableObjects scripts 0 Answers