I am creating a C# library with some reusable code and was trying to create a method inside a method. I have a method like this:
public static void Method1() { // Code }
What I would like to do is this:
public static void Method1() { public static void Method2() { } public static void Method3() { } }
Then I could choose either Method1.Method2
or Method1.Method3
. Obviously the compiler isn't happy about this, any help is much appreciated. Thanks.
you cannot directly define methods inside other methods in Java ( main method too). You should write the method in the same class as main.
Similarly another method which is Method2() is being defined with 'public' access specifier and 'void' as return type and inside that Method2() the Method1() is called. Hence, this program shows that a method can be called within another method as both of them belong to the same class.
No, not directly; however, it is possible for a method to contain a local inner class, and of course that inner class can contain methods.
Call a Method Inside main , call the myMethod() method: public class Main { static void myMethod() { System.out.println("I just got executed!"); } public static void main(String[] args) { myMethod(); } } // Outputs "I just got executed!"
If by nested method, you mean a method that is only callable within that method (like in Delphi) you could use delegates.
public static void Method1() { var method2 = new Action(() => { /* action body */ } ); var method3 = new Action(() => { /* action body */ } ); //call them like normal methods method2(); method3(); //if you want an argument var actionWithArgument = new Action<int>(i => { Console.WriteLine(i); }); actionWithArgument(5); //if you want to return something var function = new Func<int, int>(i => { return i++; }); int test = function(6); }
This answer was written before C# 7 came out. With C# 7 you can write local methods.
No, you can't do that. You could create a nested class:
public class ContainingClass { public static class NestedClass { public static void Method2() { } public static void Method3() { } } }
You'd then call:
ContainingClass.NestedClass.Method2();
or
ContainingClass.NestedClass.Method3();
I wouldn't recommend this though. Usually it's a bad idea to have public nested types.
Can you tell us more about what you're trying to achieve? There may well be a better approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With