Custom attributes in .Net Core csproj file

By Mirek on (tags: Assembly attribute, csproj, Custom attribute, .Net 5, categories: architecture, code)

Today a short guide on how to use your custom attribute in csproj file. Keep reading.

In the past we’ve put our custom attributes in AssemblyInfo.cs file. With .Net Core there is now a better place to do that. It is a .csproj project file.

Here is how to create and put a custom attribute values in there.

Let’s say we have an attribute like this:

[AttributeUsage(AttributeTargets.Assembly)]
public class MyCustomAttribute : Attribute
{
public string Value { get; set; }
public MyCustomAttribute(string value)
{
Value = value;
}
}

Then we include the attribute in csproj file providing the full attribute type name with namespace

<ItemGroup>
<AssemblyAttribute Include="MyApp.MyCustomAttribute">
<_Parameter1>your value here</_Parameter1>
</AssemblyAttribute>
</ItemGroup>

Now in the code we can access the attribute value

var assembly = typeof(App).Assembly;
var myAttr = Attribute.GetCustomAttribute(assembly, typeof(MyCustomAttribute)) as MyCustomAttribute;
var v1 = myAttr.Value;

That’s it.