Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Why can't we have inner methods / local functions?

Tags:

c#

.net

Very often it happens that I have private methods which become very big and contain repeating tasks but these tasks are so specific that it doesn't make sense to make them available to any other code part.

So it would be really great to be able to create 'inner methods' in this case.

Is there any technical (or even philosophical?) limitation that prevents C# from giving us this? Or did I miss something?

Update from 2016: This is coming and it's called a 'local function'. See marked answer.

like image 462
Marc Avatar asked Jul 31 '09 09:07

Marc


2 Answers

Well, we can have "anonymous methods" defined inside a function (I don't 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();
}
like image 193
mmx Avatar answered Oct 04 '22 16:10

mmx


If something is long and complicated than usually its good practise to refactor it to a separate class (either normal or static - depending on context) - there you can have private methods which will be specific for this functionality only.

like image 26
Grzenio Avatar answered Oct 04 '22 16:10

Grzenio