C #: Why don't we have internal methods / local functions?

It often happens that I have private methods that become very large and contain repetitive tasks, but these tasks are so specific that it makes no sense to make them available to any other part of the code.

Therefore, it would be really cool to create "internal methods" in this case.

Is there any technical (or even philosophical?) Limitation that prevents C # from giving us this? Or am I missing something?

Update since 2016: this is happening and it is called the "local function". See noticeable answer.

+7
c #
source share
7 answers

It looks like we're going to get exactly what I wanted, with Local Functions in C # 7 / Visual Studio 15 :
https://github.com/dotnet/roslyn/issues/2930

private int SomeMethodExposedToObjectMembers(int input) { int InnerMethod(bool b) { // TODO: Change return based on parameter b return 0; } var calculation = 0; // TODO: Some calculations based on input, store result in calculation if (calculation > 0) return InnerMethod(true); return InnerMethod(false); } 

It is a pity that I had to wait more than 7 years :-)

See also other answers for earlier versions of C #.

0
source share

Well, we can have “anonymous methods” defined inside a function (I do not suggest using them to organize a large method):

 void test() { Action t = () => Console.WriteLine("hello world"); // C# 3.0+ // Action t = delegate { Console.WriteLine("hello world"); }; // C# 2.0+ t(); } 
+14
source share

If something is long and complicated than usual, its good practice to reorganize it into a separate class (regular or static, depending on the context) - there you can have private methods that will be specific to this function only.

+7
source share

I know that many people do not like regions, but this is a case when they can be useful by grouping your specific methods into a region.

+2
source share

Could you give a more concrete example? After reading your post, I have the following impression, which, of course, is only a hunch, due to limited information:

  • Private methods are not available outside your class, so they are still hidden from any other code.
  • If you want to hide private methods from other code in the same class, your class may be large and may violate the single responsibility rule.
  • Look at the anonymous delegates for lambda expressions. This is not exactly what you asked for, but they can solve most of your problems.

Achim

+2
source share

If your method gets too large, consider putting it in a separate class or creating private helper methods. I usually create a new method whenever I usually write a comment.

+1
source share

The best solution is to refactor this method to split the class. Create an instance of this class as a private field in your initial class. Make the large method public and reorganize the large method into several private methods, so it will be clear what it does.

0
source share

All Articles