Search code examples
c#.netclassoopmethods

How can I use a method outside of a class without using static keyword in C#?


I'm beginner in C# programming, What I want to do is use a method out side of the class but method is unreachable, I cant do it without static keyword and I dont want to use static keyword because I'm exercising a path of achieveing what I thougt at the beginning.

In C# there may no way to do it and you might think why did I think I can do that without using static keyword is that because I learn some python before C# and in my mind I thought I can easily do that in C# too without extra coding.

Here is the example code:

public class ExampleClass
{

    public string message = "Hello World";
    public void Display()
    {
        Console.WriteLine("Hello World");
    }

    public class Class1
    {
        public void TestMethod()
        {
            // I want to use message variable
            // and Display() method here.
        }
    }
}


Solution

  • Let's simplify:

    public class Foo
    {
        public void A() {}
        public static void B() {}
    }
    
    public static class Program
    {
        public static void Main()
        {
            // writing code here...
        }
    }
    

    There's two methods we want to call: A and B. One is static, the other is not static - it's called an "instance member".

    Calling B, because it's static, is like this:

    Foo.B();
    

    in order to call A, we have to make an instance of the Foo class.

    Foo f = new Foo();
    f.A();
    

    There are only two ways to call a method in C#: either statically through it's type, or as an instance of a variable.

    If you want to use ExampleClass.message from within Class1.TestMethod, then either you need to have an instance of the ExampleClass type (declared either within the TestMethod method or as a member of the Class1 class), or ExampleClass.message needs to be static.

    I think you're going to want to really study what "static" means in C#. See a good SO post and the C# documentation.

    Fun fact, the fact that Class1 is "nested" inside ExampleClass doesn't not give it any special treatment than if it was not nested. All it does is make the type name ExampleClass.Class1.