Some Helpful Extensions When Dealing With Types in .NET

Some Helpful Extensions When Dealing With Types in .NET

Check if a Type Is Deriving From Another Type. Deriving types is a common practice. Get Type of T From IEnumerable<T> Sometimes, one needs to know the item type of an IEnumerable<T>. Check if a Type Implements a Certain Interface. Find a Type in an External Assembly.

If you are writing reusable code, chances are high that you will write quite some code that deals with types, generics, and interfaces. Over the years, the collection of my helper extensions for that have grown. As some of my upcoming posts use them, I share them (also) for future reference.

1. Check if a Type Is Deriving From Another Type

Deriving types is a common practice. To some extent, you can use pattern matching. Sometimes, that isn't enough, though (especially if you have a multi-level derivation path). This is when I use one of these two extensions:

Java

1

        public static bool IsDerivingFrom(this Type type, Type searchType)

2

        {

3

            if (type == null) throw new NullReferenceException();

4

5

            return

6

                type.BaseType != null &&

7

                (type.BaseType == searchType ||

8

                type.BaseType.IsDerivingFrom(searchType));

9

        }

10

11

        public static bool IsDerivingFromGenericType(this Type type, Type searchGenericType)

12

        {

13

            if (type == null) throw new ArgumentNullException(nameof(type));

14

            if (searchGenericType == null) throw new ArgumentNullException(nameof(searchGenericType));

15

16

            return

17

                type != typeof(object) &&

18

                (type.IsGenericType &&

19

                searchGenericType.GetGenericTypeDefinition() == searchGenericType ||

20

                IsDerivingFromGenericType(type.BaseType, searchGenericType));

21

        }

Update 1: [Type.IsSubclassOf_](https://docs.microsoft.com/en-us/dotnet/api/system.type.issubclassof?view=netcore-3.1#:~:text=You%20can%20call%20the%20IsSubclassOf%20method%20to%20determine,a%20type%20is%20an%20enumeration.%20More%20items...%20) will give you the same result as IsDerivingFrom. The main purpose was (is) to use my implementation when having multiple levels of derivation and being able to debug the whole detection process._

2. Get Type of T From IEnumerable

Sometimes, one needs to know the item type of an IEnumerable. These two extensions will help you in this case:

Java

1

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Extension method")]

2

        public static Type GetItemType<T>(this IEnumerable<T> enumerable) => typeof(T);

3

4

        public static Type? GetItemType(this object enumerable)

5

            => enumerable == null ? null :

6

            (enumerable.GetType().GetInterface(typeof(IEnumerable<>).Name)?.GetGenericArguments()[0]);

3. Check if a Type Implements a Certain Interface

Interfaces are supposed to make the life of a developer easier. Like with the type derivation, sometimes we need to know if a type implements a certain interface. This extension answers the question for you:

Java

1

        public static bool ImplementsInterface(this Type? type, Type? @interface)

2

        {

3

            bool result = false;

4

5

            if (type == null || @interface == null)

6

                return result;

7

8

            var interfaces = type.GetInterfaces();

9

            if (@interface.IsGenericTypeDefinition)

10

            {

11

                foreach (var item in interfaces)

12

                {

13

                    if (item.IsConstructedGenericType && item.GetGenericTypeDefinition() == @interface)

14

                        result = true;

15

                }

16

            }

17

            else

18

            {

19

                foreach (var item in interfaces)

20

                {

21

                    if (item == @interface)

22

                        result = true;

23

                }

24

            }

25

26

            return result;

27

        }

Update 2: [Type.IsAssignableFrom_](https://docs.microsoft.com/en-us/dotnet/api/system.type.isassignablefrom?view=netcore-3.1) will also tell you if a type implements an interface. As for the IsDerivingFrom method, I wanted to be able to debug the detection, which is - besides from having an explicit implementation - the main reason for this method._

web dev mvvm interface types type assembly extension methods dev stories helper msicc

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Types of Web Applications and their Examples

Are you wondering about how many types of web applications? Don't worry! Here we explain all types of web apps along with their characteristics.

Basic Data Types in Python | Python Web Development For Beginners

In the programming world, Data types play an important role. Each Variable is stored in different data types and responsible for various functions. Python had two different objects, and They are mutable and immutable objects.

whatsapp web-w app web-webs whatsapp »

whatsapp web-w app web-webs whatsapp-web.whatsapp.com-wsp web-web.whatsapp.com qr-whats up online-whatsappwebsite

Web Storage APIs - Pete Lepage at Google's Web.Dev

New APIs have emerged to answer the need of a web moving from documents to applications. Pete Lepage presented at web.dev LIVE a short but thorough description of the options developers have to store and cache data on the client. The CacheStorage, StorageManager and other APIs help developers create applications with offline capabilities and performance closer to native mobile applications’.

11 Extremely Useful & Best Chrome Extensions for Web Developers 2020

Working with Chrome offers access to an immense repository of Chrome extensions and tools which make our daily tasks less of a chore. 11 Extremely Useful & Best Chrome Extensions for Web Developers 2020