Home

Awesome

Namotion.Reflection

Storage | Messaging | Reflection

Azure DevOps Azure DevOps Nuget Discord

<img align="left" src="https://raw.githubusercontent.com/RicoSuter/Namotion.Reflection/master/assets/Icon.png" width="48px" height="48px">

.NET library with advanced reflection APIs like XML documentation reading, Nullable Reference Types (C# 8) reflection and string based type checks.

This library is mainly used in NJsonSchema and NSwag.

Contextual and cached types

Inheritance hierarchy:

Behavior:

Nullability reflection (C# 8)

With the ContextualType class you can reflect on the nullability of properties, fields, method parameters and return types which will be available when compiling with the C# 8 compiler with the Nullable Reference Types feature enabled.

Given the following test class with some C# 8 nullability annotations (?):

#nullable enable

public class MyClass
{
    public void MyMethod(Dictionary<string, string?> dictionary)
    {
    }
}

To reflect on the first parameter's nullability, we can load a ContextualType instance and display the nullability of the parameter's types:

using Namotion.Reflection;

var method = typeof(MyClass).GetMethod(nameof(MyClass.MyMethod));
var parameter = method.GetParameters().First();
var contextualParameter = parameter.ToContextualParameter();

Console.WriteLine("Dictionary: " + contextualParameter.Nullability);
Console.WriteLine("Key: " + contextualParameter.GenericArguments[0].Nullability);
Console.WriteLine("Value: " + contextualParameter.GenericArguments[1].Nullability);

The output is:

Dictionary: NotNullable
Key: NotNullable
Value: Nullable

For more details, see https://blog.rsuter.com/the-output-of-nullable-reference-types-and-how-to-reflect-it/

Methods:

Validate nullability (C# 8)

It is important to understand that Nullable Reference Types is a compiler feature only and the .NET runtime does not do any checks when your app is running. Consider the following class:

public class Person
{
    public string FirstName { get; set; }

    public string? MiddleName { get; set; }

    public string LastName { get; set; }
}

Inside your application you'll get warnings when you forget to set the FirstName. However when data is coming from outside (e.g. via reflection, serialization, etc.) you could end up with invalid objects. This JSON.NET call throws no exception but will create an invalid object:

var person = JsonConvert.DeserializeObject<Person>("{}");

Call the EnsureValidNullability() extension method which throws an InvalidOperationException when the object is in an invalid state:

person.EnsureValidNullability();

Methods:

Read XML Documentation

Methods:

This functionality can also be used with Cecil types with the Namotion.Reflection.Cecil package.

Extension methods

Methods:

IEnumerable extensions

Object extensions

Type extensions