Show / Hide Table of Contents

Advanced Reflection

.NEXT provides additional methods to reflect collection types, delegates and task types. These methods are located in DotNext.Reflection namespace.

Important

DotNext.Reflection library doesn't receive new features anymore and will be deprecated soon. See this post for more information.

Collection

.NET Reflection contains a method to obtain type of elements in the array. .NEXT provides special class CollectionType to reflect type of collection elements.

using DotNext.Reflection;

var itemType = typeof(List<string>).GetItemType();  //itemType == typeof(string)

This method ables to extract item type from any class implementing IEnumerable<T>, even if such class is not generic class itself.

Dispose pattern

DisposableType allows to reflect void Dispose() method from any type. The reflection checks whether the class implements IDisposable method. If not, then it looks for the public instance parameterless method Dispose with void return type.

using DotNext.Reflection;

var dispose = typeof(Stream).GetDisposeMethod();

Tasks

TaskType provides a way to obtain actual generic argument of Task.

using DotNext.Reflection;

var t = typeof(Task<int>).GetTaskType();    //t == typeof(int)
t = typeof(Task);   //t == typeof(void)

Additionally, it is possible to instantiate task type at runtime:

using DotNext.Reflection;

var t = typeof(Task<>).MakeTaskType(typeof(string));    //t == typeof(Task<string>)
  • Edit this page
☀
☾
In this article
Back to top
Supported by the .NET Foundation
☀
☾