locked
can i call static class method from non static class method in c# RRS feed

  • Question

  • User-1682137340 posted
    public class myClass
    {
        public void print(string mess)
        {
            myotherclass.print("i am static method calling from non static method");
            Console.WriteLine(mess);
        }
    }
    
    public static class myOtherClass
    {
        public static void print(string mess)
        {
            Console.WriteLine(mess);
        }
    }
    can any one help me out
    Sunday, October 30, 2016 7:22 PM

All replies

  • User303363814 posted
    Is there a compilation error? What?
    Is there a runtime exception? What?
    Do you get the expected result at runtime?
    Sunday, October 30, 2016 8:20 PM
  • User-1672470423 posted

    Yes, you can do that.

    Sunday, October 30, 2016 8:23 PM
  • User-707554951 posted

    Hi gaddamraju4u,

    As Sumit said, it is able for us call static class method from non static class method.

    A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, you cannot use the new keyword to create a variable of the class type.

    Because there is no instance variable, you access the members of a static class by using the class name itself.

    Notable Points here are:

    1. A static method can be invoked directly from the class level

    2. A static method not requires any class object

    3. Any main() method is shared through entire class scope so it always appears with static keyword.

    4. Static methods can be overloaded but not overridden, because they belong to the class, and not to any instance of the class

    Besides, I have try your code in my application like below:

      class myClass
        {
            public void LLogin(string mess)
            {
                myOtherClass.print("i am static method calling from non static method");
                Console.WriteLine(mess);
            }
        }
    class myOtherClass
        {
            public static void print(string mess)
            {
                Console.WriteLine(mess);
            }
        }
    class Program
        {
            static void Main(string[] args)
            {
                myClass myclass = new myClass();
                myclass.LLogin("i am a method in non static method");
                Console.ReadKey();
            }
    }

    Output:


    Best regards

    Cathy

    Monday, October 31, 2016 2:01 AM