-
summary
Ignore the case that an object cannot represented as an array, is it possible to define an extension(static) method like:
public static ? ToArray<TSource>(this TSource source);and returns the array of an object if it consists of whatever a sequence of elements? And if yes, what would the
?be? -
explanation
I’ve thought about the following declarations:
public static TElement[] ToArray<TElement>(this IEnumerable<TElement> source); public static ? ToArray<TSource>(this IEnumerable source);But I cannot assume an unknown class must have implemented
IEnumerable<T>orIEnumerable. I cannot even define the?in the case it is justIEnumerablewhich is out of generic definition.And I’ve also thought about the
Arrayclass:public static Array ToArray<TSource>(this TSource source);But that means the element type was unknown at compile time.
So I’m wondering is it possible to know the element type at compile time without a class implementing
IEnumerable<T>?
summary Ignore the case that an object cannot represented as an array, is it
Share
Unfortunately,
IEnumeratorpredates generics so it carries with it no type information; just aIEnumerator GetEnumerator()makingStringnot so appealing to try and force into this generic implementation you’re trying to accomplish.It’s been a long time since I’ve done C# but I imagine:
… should be fine as:
The important thing to keep in mind about extension methods is they are just syntax sugar. They don’t actually stick around or become injected into the types they are decorating. They are replaced at compile time to static method invocations. Your mileage with extension methods will vary.