Boost Your .NET Projects with Spargine: Master Type Management with TypeHelper

Spargine is a collection of open-source assemblies and NuGet packages designed for .NET 10, which I have been developing and maintaining since the release of .NET Framework 2. These assemblies are not only a core part of my projects but are also actively deployed in production environments across several companies I collaborate with.

Get Spargine

You can access the source code and NuGet packages here:

TypeHelper is a powerful utility within the DotNetTips.Spargine.Core assembly and NuGet package. It provides essential methods for type management, streamlining tasks such as:

  • Loading and discovering derived types
  • Creating new instances of types
  • Converting JSON data to objects
  • Transforming JSON files into objects
  • Generating hash codes for instances
  • Listing built-in .NET types

These features enable developers to handle types in various .NET scenarios, enhancing productivity and performance.

Methods and Properties

Below is a detailed overview of the methods provided by TypeHelper:

Type Management

  • BuiltInTypeNames()
    Lists all built-in .NET types dynamically. Currently, it detects 216 built-in types in .NET.
  • BuiltinTypes
    Returns a read-only collection of built-in .NET types.
  • IsBuiltinType(in Type type)
    Determines whether a given type is a built-in .NET type.

Type Creation and Comparison

  • Create<T>()
    Creates an instance of the specified type T.
    Supports constructor parameter injection via an overload.
  • DoesObjectEqualInstance(object value, object instance)
    Checks if the specified object is the same instance as the provided instance.
  • GetInstanceHashCode(object instance)
    Computes the hash code for a given instance.
  • Min<T>(T? obj1, T? obj2)
    Returns the minimum of two comparable objects.
  • Max<T>(T? obj1, T? obj2)
    Returns the maximum of two comparable objects.

Derived Type Discovery

  • FindDerivedTypes(AppDomain currentDomain, Type baseType, bool classOnly)
    Finds derived types within a given AppDomain.
  • FindDerivedTypes(DirectoryInfo path, SearchOption fileSearchType, Type baseType, bool classOnly)
    Searches for derived types within assemblies located in a specified directory.
  • FindDerivedTypes(Type baseType, bool classOnly)
    Searches for derived types from a specified base type in currently loaded assemblies.

JSON Serialization & Deserialization

  • FromJson<T>(in string json)
    Deserializes a JSON string into an instance of type T.
  • FromJsonFile<T>(FileInfo file)
    Deserializes a JSON file into an instance of type T.

Type Information & Properties

  • GetAllAbstractMethods(Type type)
    Returns all abstract methods defined on the specified Type.
  • GetAllConstructors(Type type)
    Gets all constructors of the specified type, including inherited constructors.
  • GetAllDeclaredFields(Type type)
    Gets all declared fields of the specified type.
  • GetAllDeclaredMethods(Type type)
    Gets all declared methods of the specified type.
  • GetAllFields(Type type)
    Gets all fields of the specified type, including inherited fields.
  • GetAllGenericMethods(Type type)
    Gets all generic methods of the specified type.
  • GetAllMethods(Type type)
    Gets all methods of the specified type, including inherited methods.
  • GetAllProperties(Type type)
    Gets all properties of the specified type, including inherited properties.
  • GetAllPublicMethods(Type type)
    Gets all public methods of the specified type.
  • GetAllStaticMethods(Type type)
    Gets all static methods of the specified type.
  • GetAttribute<TAttribute>(FieldInfo fieldInfo)
    Gets a custom attribute of the specified type from the given field.
  • GetAttribute<TAttribute>(MethodInfo methodInfo)
    Gets a custom attribute of the specified type from the given method.
  • GetAttribute<TAttribute>(PropertyInfo propertyInfo)
    Gets a custom attribute of the specified type from the given property.
  • GetAttribute<TAttribute>(Type type)
    Gets a custom attribute of the specified type from the given type.
  • GetDefault<T>()
    Retrieves the default value for a specified type T.
  • GetGenericArguments(Type type)
    Gets the generic type arguments of the specified Type.
  • GetImplementedInterfaces(object input)
    Gets the names of all interfaces implemented by the specified object’s type.
    This method is overloaded to pass in a collection of interface names.
  • GetImplementedInterfaceTypes(object input)
    Gets all interfaces implemented by the specified object’s type.
  • GetMembersWithAttribute<TAttribute>(Type type)
    Retrieves all members of a specified type that have a given attribute.
  • GetPropertyValues<T>(in T input)
    Extracts property values from an object.
  • GetTypeMembersWithAttribute<TAttribute>(Type type)
    Gets all members of the specified type that have the specified attribute.
  • HasAttribute<T>(MethodInfo methodInfo)
    Determines whether the specified method has an attribute of type.
  • HasBaseClass(Type type, Type baseClass)
    Determines whether the specified type has the specified base class.
  • HasMethod(Type type, string methodName, BindingFlags bindingFlags)
    Determines whether the specified Type has a method with the given name and binding flags.
  • HasParameterlessConstructor(Type type)
    Determines whether the specified type has a parameterless constructor.
  • HasProperty(Type type, string propertyName)
    Determines whether the specified Type has a property with the given name.
  • ImplementsInterface(Type type, Type interfaceType)
    Determines whether the specified Type implements the specified interface type.
  • IsAssignableTo(Type type, Type targetType)
    Determines whether the current Type can be assigned to the specified target type.
  • IsClosedGeneric(Type type)
    Determines whether the specified Type is a closed generic type.
  • IsEnumerable(Type type)
    Determines whether the specified implements the IEnumerable interface.
  • IsNullable(Type? type)
    Determines whether the specified Type is a nullable type.
  • IsOpenGeneric(Type type)
    Determines whether the specified Type is an open generic type definition.
  • IsStatic(PropertyInfo property)
    Determines whether the specified PropertyInfo represents a static property.

Type Display Name Formatting

  • GetTypeDisplayName(in object item, bool fullName)
    Retrieves the display name of an object’s type.
  • GetTypeDisplayName(Type type, bool fullName, bool includeGenericParameterNames, bool includeGenericParameters, char nestedTypeDelimiter)
    Returns a formatted type display name with options for generic types.
  • GetTypeDisplayName(Type type, DisplayNameOptions options)
    Generates a customizable type display name using specified formatting options.

Assembly & Generic Type Processing

  • ProcessGenericType(StringBuilder builder, Type type, Type[] genericArguments, in int length, DisplayNameOptions options)
    Processes a generic type, constructing its formatted display name.

Example

Here is an example of how I use TypeHelper in a method in Spargine.

var values = TypeHelper.GetPropertyValues(input: App.AppInfo);

if (values?.Count > 0)

{

    var items = values.OrderBy(p => p.Key).ToArray();

    if (logger.IsEnabled(LogLevel.Information))

    {

        foreach (var item in items)

        {

            logger.LogInformationMessage($"{nameof(AppInfo)}:{item.Key} - {item.Value}");

        }

    }

}

Summary

The TypeHelper class in Spargine simplifies working with types in .NET by offering optimized, high-performance methods. Whether you need to discover derived types, create instances dynamically, deserialize JSON, or format type names, TypeHelper provides efficient solutions. All methods have been benchmarked for performance improvements, with detailed results available on GitHub.

If reflection and runtime type-handling matter in your world — TypeHelper belongs in your toolbox.

Get Involved!

The success of open-source projects like Spargine relies on community contributions. If you find these updates useful or have ideas for further improvements, I encourage you to contribute by:

  • Submitting pull requests
  • Reporting issues
  • Suggesting new features

Your input is invaluable in making Spargine an even more powerful tool for the .NET community.

If you are interested in contributing or have any questions, feel free to contact me via email at dotnetdave@live.com. Your support and collaboration are greatly appreciated!

Thank you, and happy coding!

Pick up any books by David McCarter by going to Amazon.com: http://bit.ly/RockYourCodeBooks

One-Time
Monthly
Yearly

Make a one-time donation

Make a monthly donation

Make a yearly donation

Choose an amount

$5.00
$15.00
$100.00
$5.00
$15.00
$100.00
$5.00
$15.00
$100.00

Or enter a custom amount

$

Your contribution is appreciated.

Your contribution is appreciated.

Your contribution is appreciated.

DonateDonate monthlyDonate yearly

If you liked this article, please buy David a cup of Coffee by going here: https://www.buymeacoffee.com/dotnetdave

© The information in this article is copywritten and cannot be preproduced in any way without express permission from David McCarter.


Discover more from dotNetTips.com

Subscribe to get the latest posts sent to your email.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.