Skip to content

Commit 79e76b4

Browse files
author
Andreas Pouwels
committed
Added extension (GetAttribute()) to extract an attribute of an Enum or an object
1 parent 0eca97e commit 79e76b4

File tree

2 files changed

+46
-4
lines changed

2 files changed

+46
-4
lines changed

src/ZimLabs.CoreLib/ZimLabs.CoreLib/Extensions.cs

+42
Original file line numberDiff line numberDiff line change
@@ -73,4 +73,46 @@ public static string ConvertToFileSize(this FileInfo fileInfo, int divider = 102
7373
return addBytes ? $"{result} ({fileInfo.Length:N0} Bytes)" : result;
7474
}
7575
#endregion
76+
77+
#region Objects
78+
/// <summary>
79+
/// Gets the attribute of the enum
80+
/// </summary>
81+
/// <typeparam name="T">The type of the attribute</typeparam>
82+
/// <param name="value">The enum value</param>
83+
/// <returns>The attribute</returns>
84+
public static T? GetAttribute<T>(this Enum value) where T : Attribute
85+
{
86+
var memberInfo = value.GetType().GetMember(value.ToString());
87+
88+
if (memberInfo.Length == 0)
89+
return null;
90+
91+
var attributes = memberInfo[0].GetCustomAttributes(typeof(T), false);
92+
93+
foreach (var attribute in attributes)
94+
{
95+
if (attribute is T result)
96+
return result;
97+
}
98+
99+
return null;
100+
}
101+
102+
/// <summary>
103+
/// Gets the attribute of the desired object
104+
/// </summary>
105+
/// <typeparam name="T">The type of the attribute</typeparam>
106+
/// <param name="value"></param>
107+
/// <returns></returns>
108+
public static T? GetAttribute<T>(this object value) where T : Attribute
109+
{
110+
var attribute = Attribute.GetCustomAttribute(value.GetType(), typeof(T));
111+
112+
if (attribute is T result)
113+
return result;
114+
115+
return null;
116+
}
117+
#endregion
76118
}

src/ZimLabs.CoreLib/ZimLabs.CoreLib/ZimLabs.CoreLib.csproj

+4-4
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,11 @@
1212
<RepositoryUrl>https://github.com/InvaderZim85/ZimLabs.CoreLib</RepositoryUrl>
1313
<RepositoryType>git</RepositoryType>
1414
<PackageTags>helper, extensions</PackageTags>
15-
<PackageReleaseNotes>Initial release</PackageReleaseNotes>
15+
<PackageReleaseNotes>Added extension to extract a custom attribute</PackageReleaseNotes>
1616
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
17-
<AssemblyVersion>2.0.0.0</AssemblyVersion>
18-
<FileVersion>2.0.0.0</FileVersion>
19-
<Version>2.0.0</Version>
17+
<AssemblyVersion>2.0.1</AssemblyVersion>
18+
<FileVersion>2.0.1</FileVersion>
19+
<Version>2.0.1</Version>
2020
<PackageLicenseExpression>MIT</PackageLicenseExpression>
2121
<GenerateDocumentationFile>True</GenerateDocumentationFile>
2222
</PropertyGroup>

0 commit comments

Comments
 (0)