blog icon indicating copy to clipboard operation
blog copied to clipboard

[Common C# Methods]:

Open rrickgauer opened this issue 1 year ago • 0 comments

Common C# Methods

Custom Attributes

Get the custom attribute assigned to a specific property of an object:


public static TAttribute GetPropertyAttribute<TAttribute, TClass>(string propertyName) where TAttribute : Attribute
{
    return GetPropertyAttribute<TAttribute>(propertyName, typeof(TClass));
}

public static TAttribute GetPropertyAttribute<TAttribute>(string propertyName, Type classType) where TAttribute : Attribute
{
    var prop = classType.GetProperty(propertyName);

    if (prop is null)
    {
        throw new NotSupportedException($"{propertyName} is not a valid property for type {t}");
    }

    var attr = prop.GetCustomAttribute<TAttribute>();

    if (attr is null)
    {
        throw new NotSupportedException($"{propertyName} does not have ${nameof(TAttribute)} assignment");
    }

    return attr;
}

Copy Properties

To copy over the property values with matching names from one object to another:

public static void CopyOverProperties<TSource, TTarget>(TSource source, TTarget target)
{
    var sourceProperties = typeof(TSource).GetProperties().Where(p => p.CanRead);
    var targetProperties = typeof(TTarget).GetProperties().Where(p => p.CanWrite);

    foreach (var prop in sourceProperties)
    {
        var sourceValue = prop.GetValue(source);

        var targetProperty = targetProperties.Where(p => p.Name == prop.Name).FirstOrDefault();
        targetProperty?.SetValue(target, sourceValue);
    }
}

Enum Utilities

To generate a collection of each value in an enum:

public static IEnumerable<TEnum> GetEnumEntries<TEnum>() where TEnum : Enum
{
    return Enum.GetValues(typeof(TEnum)).Cast<TEnum>();
}

rrickgauer avatar Oct 04 '23 00:10 rrickgauer