Generics – Convert Array to T

I have a problem I can't get through. I'm writting library which get properties through reflection from given object and I've got blocked on final step – converting value to its output type.

protected T Convert(object obj) { var type = obj.GetType(); if (type.IsArray && typeof(T).IsArray) { var result = Array.CreateInstance(typeof(T).GetElementType(), ((Array)obj).Length); for (int i = 0; i < result.Length; i++) { result.SetValue(ConvertSingle(((Array)obj).GetValue(i)), i); } return (T)result; //problem here } else { return ConvertSingle(obj); } } 

I can not convert System.Array to T (syntax error). I can't return result as T as I still want it to work with structures (int, string etc). Does someone got any idea how to overcome this?

by tedeusz via /r/csharp

Leave a Reply