Daily Knowledge Drop
When using local functions
, it is possible to decorate them, as well as their parameters, with attributes
.
Local function
Local functions
are methods of a type that are nested in another member. They can only be called from their containing member:
public class Processor
{
// Containing method
public void DoProcessing()
{
// local function/method
void PerformInternalLogic()
{
Console.WriteLine("Logic being performed...");
}
PerformInternalLogic();
}
}
In the above sample, the PerformInternalLogic method is a local method
nested in the DoProcessing method, and can only be called from within the method.
Attributes
Method attribute
Method targeting attributes can be used on local functions:
public class Processor
{
// Containing method
public void DoProcessing()
{
// local function/method
[Obsolete("This will be deprecated. Not useful for consumers of your method")]
void PerformInternalLogic()
{
Console.WriteLine("Logic being performed...");
}
PerformInternalLogic();
}
}
In the above, the Obsolete
attribute was used to decorate the PerformInternalLogic method (as an indicator that the local method is obsolete and will be removed in future)
Parameter attribute
Parameter targeting attributes can also be used on local function parameters:
public class Processor
{
// Containing method
public void DoProcessing()
{
// local function/method
[Obsolete("This will be deprecated. Not useful for consumers of your method")]
void PerformInternalLogic()
{
Console.WriteLine("Logic being performed...");
}
// local function/method
void PerformOtherInternalLogic([CallerMemberName] string memberName = "")
{
Console.WriteLine($"Logic being performed called from {memberName}");
}
PerformInternalLogic();
PerformOtherInternalLogic();
}
}
Here, the CallerMemberName
attribute us applied to the parameter of the PerformOtherInternalLogic method.
Notes
A fairly niche use case, but if required, it is useful to know it is possible to add attributes to local functions.
References
8. Attributes on Local Functions
Daily Drop 204: 17-11-2022
At the start of 2022 I set myself the goal of learning one new coding related piece of knowledge a day.
It could be anything - some.NET / C# functionality I wasn't aware of, a design practice, a cool new coding technique, or just something I find interesting. It could be something I knew at one point but had forgotten, or something completely new, which I may or may never actually use.
The Daily Drop is a record of these pieces of knowledge - writing about and summarizing them helps re-enforce the information for myself, as well as potentially helps others learn something new as well.