I want 'local functions'. Or 'embedded functions' if you like. Javascript already has them, thanks to its functional programming basis. The problem is, I want to implement a piece of my algorithm as a function, but I don't want to publish it to other methods in that class. The think I'm looking for is written some like this in javascript:
function mainfunc()
{
var subfunc = function(args) { .... }
}
I dream about something like this in c#:
public void mainfunc()
{
bool subfunc(int args) { ... }
}
Or we can extend something we already have, labels, to 'parameterized labels'. It doesn't satisfy the requirement in my mind, because label-goto pairs cause a different impact on the program flow, which may lead to extra complexity of your overall algorithm. Parameterized labels may seem like this, in c#:
public string mainfunc(
{
if (...some condition...)
goto returnOne("foo");
else
goto returnTwo("zoo", "(two)");
// do some unrelated stuff
returnOne(string s):
return s+"(one)";
returnTwo(string s, string s2):
MessageBox.Show(s, s2);
return s+s2;
}
As you can see, it becomes something else, but it's still useful. It was also possible to do the same with the help of some variables and a couple of if statements, but I think this adds to readability and overall maintainability of the code. Of course it may also lead to that exaggerated old saying about 'spagetti code', but it depends on how careful you use labels and how much you care about overall simplicity of the code.
5 comments:
try lambda expressions: http://msdn.microsoft.com/en-us/library/bb397687.aspx
Umm, I had thought delegates are inappropriate because they require a seperate declaration. But in .net 3.5 you can use Func<,,,> generic delegate to easily define an interface in the same line. It's not so bad, you're right.
On the other hand, lambda expressions (or generally, delegates) are a bit different than normal function calls, since they have a symbolic reference to given arguments, instead of value passing. This may lead to some unexpected results if you don't distinguish them from functions.
In C# you can't have methods inside methods, but you *can* have classes inside classes. Perhaps you could get the effect you want by having an inner class with one public method and a number of private methods? Inner classes have access to everything in their outer class, including private members, they can be private themselves to hide them from the outside world, and the outer class only has access to the public members of the inner class.
however, you can not have classes inside methods(!)
thus your suggestion doesn't satisfy Görkem's fantasies :)
Post a Comment