Class TypeDecoratorExtensions
- Namespace
- Cuemon
- Assembly
- Cuemon.Core.dll
Extension methods for the Type class hidden behind the IDecorator<T> interface.
public static class TypeDecoratorExtensions
- Inheritance
-
TypeDecoratorExtensions
Examples
TypeDecoratorExtensions provides extension methods on Decorator.Enclose for deep reflection inspection of .NET types, including member enumeration, interface detection, attribute checking, and circular-reference detection. This example wraps AuditedOrder (annotated with [DataContract]) and calls GetAllProperties, GetAllFields, GetAllEvents, and GetAllMethods to enumerate members across the full hierarchy including its base TrackedEntity. It also uses predicate methods like HasTypes (for FileStream → Stream), HasInterfaces, HasAttribute, HasEnumerableImplementation, IsNullable, and HasAnonymousCharacteristics to classify type capabilities. Console output includes sorted member names, boolean capability flags, default values such as 00000000-0000-0000-0000-000000000000 for Guid, friendly type names like IList<String>, and circular-reference detection results for a LinkedNode with a self-referencing loop.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using Cuemon;
namespace Contoso.Reflection;
public sealed class TypeDecoratorExtensionsExample
{
public static void Run()
{
var orderType = Decorator.Enclose(typeof(AuditedOrder));
var streamType = Decorator.Enclose(typeof(Stream));
var propertyNames = orderType.GetAllProperties().Select(property => property.Name).OrderBy(name => name).ToArray();
var fieldNames = orderType.GetAllFields().Select(field => field.Name).OrderBy(name => name).ToArray();
var eventNames = orderType.GetAllEvents().Select(@event => @event.Name).OrderBy(name => name).ToArray();
var methodNames = orderType
.GetAllMethods()
.Where(method => method.DeclaringType == typeof(AuditedOrder) && !method.IsSpecialName)
.Select(method => method.Name)
.Distinct()
.OrderBy(name => name)
.ToArray();
var orderOnlyProperties = orderType.GetRuntimePropertiesExceptOf<TrackedEntity>().Select(property => property.Name).OrderBy(name => name).ToArray();
bool hasTypes = Decorator.Enclose(typeof(FileStream)).HasTypes(typeof(Stream));
bool hasInterfaces = Decorator.Enclose(typeof(List<>)).HasInterfaces(typeof(IEnumerable<>));
bool hasAttribute = orderType.HasAttribute(typeof(DataContractAttribute), typeof(DataMemberAttribute));
bool hasComparable = Decorator.Enclose(typeof(string)).HasComparableImplementation();
bool hasComparer = Decorator.Enclose(typeof(StringComparer)).HasComparerImplementation();
bool hasDictionary = Decorator.Enclose(typeof(ReadOnlyDictionary<int, string>)).HasDictionaryImplementation();
bool hasEqualityComparer = Decorator.Enclose(typeof(StringComparer)).HasEqualityComparerImplementation();
bool hasEnumerable = Decorator.Enclose(typeof(ConcurrentBag<int>)).HasEnumerableImplementation();
bool hasKeyValuePair = Decorator.Enclose(typeof(KeyValuePair<string, int>)).HasKeyValuePairImplementation();
bool isNullable = Decorator.Enclose(typeof(int?)).IsNullable();
bool hasAnonymousCharacteristics = Decorator.Enclose(new { ReferenceNumber = "PO-42" }.GetType()).HasAnonymousCharacteristics();
bool hasDefaultCtor = Decorator.Enclose(typeof(MemoryStream)).HasDefaultConstructor();
bool isComplex = streamType.IsComplex();
object defaultValue = Decorator.Enclose(typeof(Guid)).GetDefaultValue();
string friendlyName = Decorator.Enclose(typeof(IList<string>)).ToFriendlyName();
MethodBase publishMethod = orderType.MatchMember(nameof(AuditedOrder.Publish));
bool inheritedIncludesObject = streamType.GetInheritedTypes().Contains(typeof(object));
bool derivedIncludesMemoryStream = streamType.GetDerivedTypes().Contains(typeof(MemoryStream));
bool hierarchyIncludesFileStream = streamType.GetHierarchyTypes().Contains(typeof(FileStream));
var loop = LinkedNode.CreateLoop();
bool hasCircularReference = Decorator.Enclose(typeof(LinkedNode)).HasCircularReference(loop, maxDepth: 1);
Console.WriteLine(string.Join(", ", propertyNames));
Console.WriteLine(string.Join(", ", fieldNames));
Console.WriteLine(string.Join(", ", eventNames));
Console.WriteLine(string.Join(", ", methodNames));
Console.WriteLine(string.Join(", ", orderOnlyProperties));
Console.WriteLine($"{hasTypes}, {hasInterfaces}, {hasAttribute}");
Console.WriteLine($"{hasComparable}, {hasComparer}, {hasDictionary}, {hasEqualityComparer}, {hasEnumerable}, {hasKeyValuePair}");
Console.WriteLine($"{isNullable}, {hasAnonymousCharacteristics}, {hasDefaultCtor}, {isComplex}");
Console.WriteLine(defaultValue);
Console.WriteLine(friendlyName);
Console.WriteLine(publishMethod.Name);
Console.WriteLine($"{inheritedIncludesObject}, {derivedIncludesMemoryStream}, {hierarchyIncludesFileStream}, {hasCircularReference}");
}
}
[DataContract]
public sealed class AuditedOrder : TrackedEntity
{
public string PublicNote;
[DataMember]
public string ReferenceNumber { get; set; } = string.Empty;
public string Status { get; set; } = string.Empty;
public event EventHandler Published;
public void Publish()
{
Published?.Invoke(this, EventArgs.Empty);
}
}
public abstract class TrackedEntity
{
public DateTime CreatedAt { get; set; }
}
public sealed class LinkedNode
{
public LinkedNode Next { get; set; }
public static LinkedNode CreateLoop()
{
var node = new LinkedNode();
node.Next = node;
return node;
}
}
Methods
GetAllEvents(IDecorator<Type>, Action<MemberReflectionOptions>)
Retrieves a collection that represents all events defined on the enclosed Type of the specified decorator and its inheritance chain.
public static IEnumerable<EventInfo> GetAllEvents(this IDecorator<Type> decorator, Action<MemberReflectionOptions> setup = null)
Parameters
decoratorIDecorator<Type>The Type to extend.
setupAction<MemberReflectionOptions>The MemberReflectionOptions which may be configured.
Returns
- IEnumerable<EventInfo>
An IEnumerable<T> that contains all EventInfo objects on the enclosed Type of the specified
decoratorand its inheritance chain.
GetAllFields(IDecorator<Type>, Action<MemberReflectionOptions>)
Retrieves a collection that represents all fields defined on the enclosed Type of the specified decorator and its inheritance chain.
public static IEnumerable<FieldInfo> GetAllFields(this IDecorator<Type> decorator, Action<MemberReflectionOptions> setup = null)
Parameters
decoratorIDecorator<Type>The Type to extend.
setupAction<MemberReflectionOptions>The MemberReflectionOptions which may be configured.
Returns
- IEnumerable<FieldInfo>
An IEnumerable<T> that contains all FieldInfo objects on the enclosed Type of the specified
decoratorand its inheritance chain.
GetAllMethods(IDecorator<Type>, Action<MemberReflectionOptions>)
Retrieves a collection that represents all methods defined on the enclosed Type of the specified decorator and its inheritance chain.
public static IEnumerable<MethodInfo> GetAllMethods(this IDecorator<Type> decorator, Action<MemberReflectionOptions> setup = null)
Parameters
decoratorIDecorator<Type>The Type to extend.
setupAction<MemberReflectionOptions>The MemberReflectionOptions which may be configured.
Returns
- IEnumerable<MethodInfo>
An IEnumerable<T> that contains all MethodInfo objects on the enclosed Type of the specified
decoratorand its inheritance chain.
GetAllProperties(IDecorator<Type>, Action<MemberReflectionOptions>)
Retrieves a collection that represents all properties defined on the enclosed Type of the specified decorator and its inheritance chain.
public static IEnumerable<PropertyInfo> GetAllProperties(this IDecorator<Type> decorator, Action<MemberReflectionOptions> setup = null)
Parameters
decoratorIDecorator<Type>The Type to extend.
setupAction<MemberReflectionOptions>The MemberReflectionOptions which may be configured.
Returns
- IEnumerable<PropertyInfo>
An IEnumerable<T> that contains all PropertyInfo objects on the enclosed Type of the specified
decoratorand its inheritance chain.
GetDefaultValue(IDecorator<Type>)
Gets the default value from the underlying Type of the decorator.
public static object GetDefaultValue(this IDecorator<Type> decorator)
Parameters
decoratorIDecorator<Type>
Returns
Remarks
Usage is primarily intended for struct.
Exceptions
- ArgumentNullException
decoratorcannot be null.
GetDerivedTypes(IDecorator<Type>, params Assembly[])
Gets a collection (self-to-derived) of derived / descendant types from the underlying Type of the decorator.
public static IEnumerable<Type> GetDerivedTypes(this IDecorator<Type> decorator, params Assembly[] assemblies)
Parameters
decoratorIDecorator<Type>The IDecorator<T> to extend.
assembliesAssembly[]The assemblies to include in the search of derived types.
Returns
- IEnumerable<Type>
An IEnumerable<T> that contains the derived types from the underlying Type of the
decorator.
Exceptions
- ArgumentNullException
decoratorcannot be null.
GetHierarchyTypes(IDecorator<Type>, params Assembly[])
Gets a collection (inherited-to-self-to-derived) of inherited / ancestor and derived / descendant types from the underlying Type of the decorator.
public static IEnumerable<Type> GetHierarchyTypes(this IDecorator<Type> decorator, params Assembly[] assemblies)
Parameters
decoratorIDecorator<Type>The IDecorator<T> to extend.
assembliesAssembly[]The assemblies to include in the search of derived types.
Returns
- IEnumerable<Type>
An IEnumerable<T> that contains a sorted (base-to-derived) collection of inherited and derived types from the underlying Type of the
decorator.
Exceptions
- ArgumentNullException
decoratorcannot be null.
GetInheritedTypes(IDecorator<Type>)
Gets a collection (inherited-to-self) of inherited / ancestor types from the underlying Type of the decorator.
public static IEnumerable<Type> GetInheritedTypes(this IDecorator<Type> decorator)
Parameters
decoratorIDecorator<Type>The IDecorator<T> to extend.
Returns
- IEnumerable<Type>
An IEnumerable<T> that contains the inherited types from the underlying Type of the
decorator.
Exceptions
- ArgumentNullException
decoratorcannot be null.
GetRuntimePropertiesExceptOf<T>(IDecorator<Type>)
Retrieves a collection that represents all the properties defined on the enclosed Type of the decorator except those defined on T.
public static IEnumerable<PropertyInfo> GetRuntimePropertiesExceptOf<T>(this IDecorator<Type> decorator)
Parameters
decoratorIDecorator<Type>The IDecorator<T> to extend.
Returns
- IEnumerable<PropertyInfo>
A collection of properties for the enclosed Type of the
decoratorexcept those defined onT.
Type Parameters
TThe type to exclude properties on the enclosed Type of the
decorator.
Exceptions
- ArgumentNullException
decoratorcannot be null.
HasAnonymousCharacteristics(IDecorator<Type>)
Determines whether the underlying Type of the decorator suggest an anonymous implementation (be that in a form of a type, delegate or lambda expression).
public static bool HasAnonymousCharacteristics(this IDecorator<Type> decorator)
Parameters
decoratorIDecorator<Type>The IDecorator<T> to extend.
Returns
- bool
trueif the underlying Type of thedecoratorsuggest an anonymous implementation; otherwise,false.
Remarks
If you can avoid it, don't use this method. It is - to say the least - fragile.
Exceptions
- ArgumentNullException
decoratorcannot be null.
HasAttribute(IDecorator<Type>, params Type[])
Determines whether the underlying Type of the decorator implements one or more of the specified attributeTypes.
public static bool HasAttribute(this IDecorator<Type> decorator, params Type[] attributeTypes)
Parameters
decoratorIDecorator<Type>The IDecorator<T> to extend.
attributeTypesType[]The attribute types to be matched against.
Returns
- bool
trueif the underlying Type of thedecoratorimplements one or more of the specifiedattributeTypes; otherwise,false.
Exceptions
- ArgumentNullException
decoratorcannot be null -or-attributeTypescannot be null.
HasCircularReference(IDecorator<Type>, object, int, Func<object, PropertyInfo, object>)
Determines whether the specified source (which type must be the same as the underlying Type of the decorator) has a circular reference.
public static bool HasCircularReference(this IDecorator<Type> decorator, object source, int maxDepth = 2, Func<object, PropertyInfo, object> valueResolver = null)
Parameters
decoratorIDecorator<Type>The IDecorator<T> to extend.
sourceobjectThe source to check for circular reference.
maxDepthintThe maximum depth to traverse of
source.valueResolverFunc<object, PropertyInfo, object>The function delegate that is invoked when a property can be read and is of same type as the underlying Type of the
decorator.
Returns
- bool
trueif the specifiedsourcehas a circular reference; otherwise,false.
Exceptions
- ArgumentNullException
decoratorcannot be null.- InvalidOperationException
sourcehas a different type than the underlying type ofdecorator.
HasComparableImplementation(IDecorator<Type>)
Determines whether the underlying Type of the decorator implements either IComparable or IComparable<T>.
public static bool HasComparableImplementation(this IDecorator<Type> decorator)
Parameters
decoratorIDecorator<Type>The IDecorator<T> to extend.
Returns
- bool
trueif the underlying Type of thedecoratorimplements either IComparable or IComparable<T>; otherwise,false.
Exceptions
- ArgumentNullException
decoratorcannot be null.
HasComparerImplementation(IDecorator<Type>)
Determines whether the underlying Type of the decorator implements either IComparer or IComparer<T>.
public static bool HasComparerImplementation(this IDecorator<Type> decorator)
Parameters
decoratorIDecorator<Type>The IDecorator<T> to extend.
Returns
- bool
trueif the underlying Type of thedecoratorimplements either IComparer or IComparer<T>; otherwise,false.
Exceptions
- ArgumentNullException
decoratorcannot be null.
HasDefaultConstructor(IDecorator<Type>)
Determines whether the underlying Type of the decorator has a default constructor.
public static bool HasDefaultConstructor(this IDecorator<Type> decorator)
Parameters
decoratorIDecorator<Type>
Returns
Exceptions
- ArgumentNullException
decoratorcannot be null.
HasDictionaryImplementation(IDecorator<Type>)
Determines whether the underlying Type of the decorator implements either IDictionary, IDictionary<TKey, TValue> or IReadOnlyDictionary<TKey, TValue>.
public static bool HasDictionaryImplementation(this IDecorator<Type> decorator)
Parameters
decoratorIDecorator<Type>The IDecorator<T> to extend.
Returns
- bool
trueif the underlying Type of thedecoratorimplements either IDictionary, IDictionary<TKey, TValue> or IReadOnlyDictionary<TKey, TValue>; otherwise,false.
Exceptions
- ArgumentNullException
decoratorcannot be null.
HasEnumerableImplementation(IDecorator<Type>)
Determines whether the underlying Type of the decorator implements either IEnumerable or IEnumerable<T>.
public static bool HasEnumerableImplementation(this IDecorator<Type> decorator)
Parameters
decoratorIDecorator<Type>The IDecorator<T> to extend.
Returns
- bool
trueif the underlying Type of thedecoratorimplements either IEnumerable or IEnumerable<T>; otherwise,false.
Exceptions
- ArgumentNullException
decoratorcannot be null.
HasEqualityComparerImplementation(IDecorator<Type>)
Determines whether the underlying Type of the decorator implements either IEqualityComparer or IEqualityComparer<T>.
public static bool HasEqualityComparerImplementation(this IDecorator<Type> decorator)
Parameters
decoratorIDecorator<Type>The IDecorator<T> to extend.
Returns
- bool
trueif the underlying Type of thedecoratorimplements either IEqualityComparer or IEqualityComparer<T>; otherwise,false.
Exceptions
- ArgumentNullException
decoratorcannot be null.
HasInterfaces(IDecorator<Type>, params Type[])
Determines whether the underlying Type of the decorator implements one or more of the specified interfaceTypes.
public static bool HasInterfaces(this IDecorator<Type> decorator, params Type[] interfaceTypes)
Parameters
decoratorIDecorator<Type>The IDecorator<T> to extend.
interfaceTypesType[]The interface types to be matched against.
Returns
- bool
trueif the underlying Type of thedecoratorimplements one or more of the specifiedinterfaceTypes; otherwise,false.
Exceptions
- ArgumentNullException
decoratorcannot be null -or-interfaceTypescannot be null.
HasKeyValuePairImplementation(IDecorator<Type>)
Determines whether the underlying Type of the decorator implements either DictionaryEntry or KeyValuePair<TKey, TValue>.
public static bool HasKeyValuePairImplementation(this IDecorator<Type> decorator)
Parameters
decoratorIDecorator<Type>The IDecorator<T> to extend.
Returns
- bool
trueif the underlying Type of thedecoratorimplements either DictionaryEntry or KeyValuePair<TKey, TValue>.; otherwise,false.
Exceptions
- ArgumentNullException
decoratorcannot be null.
HasTypes(IDecorator<Type>, params Type[])
Determines whether the enclosed Type of the decorator contains one or more of the specified types.
public static bool HasTypes(this IDecorator<Type> decorator, params Type[] types)
Parameters
decoratorIDecorator<Type>The IDecorator<T> to extend.
typesType[]The types to be matched against.
Returns
- bool
trueif the enclosed Type of thedecoratorcontains one or more of the specifiedtypes; otherwise,false.
Exceptions
- ArgumentNullException
decoratorcannot be null -or-typescannot be null.
IsComplex(IDecorator<Type>)
Determines whether the underlying Type of the decorator is considered complex in its nature.
public static bool IsComplex(this IDecorator<Type> decorator)
Parameters
decoratorIDecorator<Type>The IDecorator<T> to extend.
Returns
- bool
trueif the underlying Type of thedecoratoris considered complex in its nature; otherwise,false.
Exceptions
- ArgumentNullException
decoratorcannot be null.
IsNullable(IDecorator<Type>)
public static bool IsNullable(this IDecorator<Type> decorator)
Parameters
decoratorIDecorator<Type>The IDecorator<T> to extend.
Returns
Exceptions
- ArgumentNullException
decoratorcannot be null.
MatchMember(IDecorator<Type>, string, Action<MethodBaseOptions>)
Conduct a search for memberName using the specified setup on the underlying Type of the decorator.
public static MethodBase MatchMember(this IDecorator<Type> decorator, string memberName, Action<MethodBaseOptions> setup = null)
Parameters
decoratorIDecorator<Type>The IDecorator<T> to extend.
memberNamestringThe name of the member on the underlying Type of the
decorator.setupAction<MethodBaseOptions>The MethodBaseOptions which may be configured.
Returns
- MethodBase
A MethodBase object representing the method that matches the specified requirements, if found on the underlying Type of the
decorator; otherwise,null.
Exceptions
- ArgumentNullException
decoratorcannot be null -or-memberNamecannot be null.- ArgumentException
memberNamecannot be empty or consist only of white-space characters.
ToFriendlyName(IDecorator<Type>, Action<TypeNameOptions>)
public static string ToFriendlyName(this IDecorator<Type> decorator, Action<TypeNameOptions> setup = null)
Parameters
decoratorIDecorator<Type>The IDecorator<T> to extend.
setupAction<TypeNameOptions>The TypeNameOptions which may be configured.
Returns
Exceptions
- ArgumentNullException
decoratorcannot be null.