• Stars
    star
    202
  • Rank 193,691 (Top 4 %)
  • Language
    C#
  • License
    MIT License
  • Created over 5 years ago
  • Updated 7 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

.NET library with advanced reflection APIs.

Namotion.Reflection

Storage | Messaging | Reflection

Azure DevOps Azure DevOps Nuget Discord

.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:

  • CachedType: A cached Type object which does not have a context
    • ContextualType: A cached Type with contextual attributes (e.g. property attributes)
      • ContextualParameterInfo
      • ContextualMemberInfo
        • ContextualMethodInfo
        • ContextualAccessorInfo
          • ContextualPropertyInfo
          • ContextualFieldInfo

Behavior:

  • Each CachedType instance is cached per Type, ParameterInfo or MemberInfo.
  • Contextual and type attributes are evaluated only once and then cached for higher performance.
  • If the original Type is Nullable<T> then T is unwrapped and stored in the Type property - the original type can be accessed with the OriginalType property.

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:

  • CachedType.ClearCache()

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:

  • HasValidNullability();
  • EnsureValidNullability();
  • ValidateNullability();

Read XML Documentation

Methods:

  • Type|MemberInfo.GetXmlDocsSummaryAsync():

  • Type|MemberInfo.GetXmlDocsRemarksAsync():

  • ParameterInfo.GetXmlDocsAsync(): Gets the parameter's description

  • ParameterInfo.GetXmlDocsElementAsync(): Gets the XElement of the given type

  • ... and more

  • XmlDocs.ClearCache()

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

Extension methods

Methods:

IEnumerable extensions

  • GetAssignableToTypeName(): Gets all objects which are assignable to the given type name as string.
  • FirstAssignableToTypeNameOrDefault(): Tries to get the first object which is assignable to the given type name as string.
  • GetCommonBaseType(): Finds the first common base type of the given types.

Object extensions

  • HasProperty(): Determines whether the specified property name exists.
  • TryGetPropertyValue(): Returns the value of the given property or null if the property does not exist.

Type extensions

  • IsAssignableToTypeName()
  • InheritsFromTypeName()
  • GetEnumerableItemType()
  • GetDisplayName(): Gets a human readable identifier for the type (eg. "DictionaryOfStringAndInt32").

More Repositories

1

NSwag

The Swagger/OpenAPI toolchain for .NET, ASP.NET Core and TypeScript.
C#
6,680
star
2

NJsonSchema

JSON Schema reader, generator and validator for .NET
C#
1,325
star
3

DNT

DNT (DotNetTools): Command line tools to manage .NET projects and solutions.
C#
397
star
4

MyToolkit

MyToolkit for .NET
C#
335
star
5

VisualJsonEditor

A JSON schema based file editor for Windows.
C#
333
star
6

NuGetReferenceSwitcher

Visual Studio extension to switch between NuGet and project references.
C#
207
star
7

SigSpec

Specification and code generator for SignalR Core.
C#
156
star
8

ProjectDependencyBrowser

Application to browse, sort, filter and launch your Visual Studio projects.
C#
46
star
9

Namotion.Messaging

.NET abstractions and implementations for message brokers, event queues and data ingestion services.
C#
46
star
10

Namotion.Storage

.NET abstractions and implementations for storage services like blob storages, file systems or object storages.
C#
35
star
11

PowerCmd

PowerCmd: The Windows Prompt replacement.
C#
33
star
12

NConsole

NConsole is a .NET library to parse command line arguments and execute commands.
C#
31
star
13

HomeBlaze

Home Automation with .NET/Blazor
C#
12
star
14

DotNetMicroservice

C#
11
star
15

InsideAsyncAwait

C#
8
star
16

aurelia-bs

Bootstrap UI (CSS framework) components for Aurelia JS.
TypeScript
7
star
17

ShopOnCore

C#
7
star
18

AureliaBootstrapDialogs

JavaScript
6
star
19

SampleOutputProcessorActionFilter

Sample application for a blog article.
C#
5
star
20

ScopeCheckingNinjectKernel

C#
3
star
21

DockerDemo

ASP.NET Core with Docker sample and tutorial
C#
3
star
22

SampleWcfService

Sample application for a blog article.
C#
3
star
23

VistoJS

Visto JavaScript Framework (VistoJS)
TypeScript
2
star
24

SampleSortableChildCollectionForm

Sample ASP.NET MVC application with edit form for an entity with a collection property.
CSS
2
star
25

SampleEfMigrationsApplication

C#
2
star
26

RicoSuter

1
star
27

SampleProjectRepository

Sample projects for package and dependency management tests.
C#
1
star
28

MdFileWiki

C#
1
star