Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method Within A Method

Tags:

methods

c#

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.

like image 397
Bali C Avatar asked Nov 15 '11 10:11

Bali C


People also ask

Can we write method in method?

you cannot directly define methods inside other methods in Java ( main method too). You should write the method in the same class as main.

Can I call a method inside another method?

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.

Can methods have methods?

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.

How do you call a method inside a method in Java?

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!"


2 Answers

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); } 
like image 156
Ray Avatar answered Sep 24 '22 01:09

Ray


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.

like image 37
Jon Skeet Avatar answered Sep 25 '22 01:09

Jon Skeet