MethodStatic keyword for local functions #3272
-
The local function feature was introduced with C# 7.0. This allowed us to declare a method inside the body of another method. I often come into situations where i don't want to access the context of the containing method, but the context of the containing class. Therefore a keyword which prohibits the local function accessing the context of the containing function, but allows it to access other members of the containing class would be useful. Here an example: class MethodStaticExample
{
private string _field;
public MethodStaticExample()
{
_field = "Hello world";
}
public string DoSomeStuff(string input)
{
return DoFurtherStuff(input);
//mstatic does not allow this local function to access `input` of the containing method, but accessing `_field` is ok
mstatic string DoFurtherStuff(string input)
{
return string.Join(" ", $"{input} {_field}".Split(' ').Reverse());
}
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
Maybe that's an overuse of local functions --> just use a (regular) method instead? |
Beta Was this translation helpful? Give feedback.
-
Or just pass 'this' into the local function. |
Beta Was this translation helpful? Give feedback.
-
Now that attributes are allowed on local functions, this is a perfect scenario for an analyzer |
Beta Was this translation helpful? Give feedback.
Now that attributes are allowed on local functions, this is a perfect scenario for an analyzer