Bali C Bali C - 3 months ago 9
C# Question

Method Within A Method

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.

Answer

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.