I'm looking at the CallerMemberName Attribute. When you specify a method like this
public void TraceInfo(string propertyName, [CallerMemberName] string memberName)
We get a compile time error stating that
Parameter with caller info must have a default value
The CallerMemberName Attribute is sealed, I would like to enforce having a default parameter like this class does
How can I enforce the same policy for having defaults on a regular attribute class?
[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
public sealed class DefaultEnforcedAttribute : Attribute
{
public DefaultEnforcedAttribute()
{
}
}
Those verifications are done at compile-time, thus, they should be implemented by the compiler.
The good news is since the inception of compiler platform Roslyn, you can implement visitors so you can extend C# compiler with your custom verifications.
I would start reading these other Q&As to see a sample of checking things using Roslyn:
Also, you should read Roslyn's official docs, specially this article: Getting Started C# Syntax Analysis. Also see C# and Visual Basic - Use Roslyn to Write a Live Code Analyzer for Your API
Finally, you might want to download and install .NET Compiler Platform SDK.
Another old-school approach which would be integrated as part of the project build it can be an MSBuild target calling a MSBuild task implemented in C# which could load the assembly that has been built using the AfterTargets
attribute on <Target>
with the value "AfterBuild"
. It would look as follows:
<Target Name="EnforcePostCompilationRules" AfterTargets="AfterBuild">
<EnforceMethodParameterDefaultValue />
</Target>
That task would load the whole assembly and using reflection it would look for all types with methods having parameters using some attribute. If some parameter has an attribute to enforce default parameter values but the parameter has no default value, you throw a build error with a meaningful message pointing out which method failed the whole validation.
Perhaps you got excited about the wider possibilities that Roslyn brings to you. Check this Q&A on which someone has answered that installing Visual Studio extensions is possible wrapping it as a NuGet package: