Static Method from a Non-Static Method and Vice versa

✅ Calling Static Method from Non-Static Method

and

✅ Calling Non-Static Method from Static Method

across different namespaces.

🗂 Project Structure:

We’ll use:

  • Utilities namespace → contains both static and non-static methods.

  • MainApp namespace → the main program to demonstrate calls.


✅ Step 1: Static Method in Utilities.Calculator


// File: Calculator.cs
namespace Utilities
{
    public static class Calculator
    {
        public static int Add(int a, int b)
        {
            return a + b;
        }
    }
}

✅ Step 2: Non-Static Method in Utilities.Helper


// File: Helper.cs
namespace Utilities
{
    public class Helper
    {
        public string GetGreeting(string name)
        {
            return $"Hello, {name}!";
        }
    }
}

✅ Step 3: Main Program – Calling Methods in MainApp


// File: Program.cs
using System;
using Utilities; // Needed to access Calculator and Helper

namespace MainApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("=== Calling Static Method from Non-Static Method ===");
            Program p = new Program();
            p.UseStaticMethod();

            Console.WriteLine("\n=== Calling Non-Static Method from Static Method ===");
            CallNonStaticFromStatic();
        }

        // Calling static method from non-static method
        public void UseStaticMethod()
        {
            int result = Calculator.Add(10, 20); // Static method call
            Console.WriteLine("Result of Calculator.Add(10, 20): " + result);
        }

        // Calling non-static method from static method
        public static void CallNonStaticFromStatic()
        {
            Helper helper = new Helper(); // Create object of Helper
            string message = helper.GetGreeting("John");
            Console.WriteLine("Greeting: " + message);
        }
    }
}





✅ Output:


=== Calling Static Method from Non-Static Method ===
Result of Calculator.Add(10, 20): 30

=== Calling Non-Static Method from Static Method ===
Greeting: Hello, John!

✅ Explanation Summary

ScenarioExample UsedNotes
Static method in different namespaceCalculator.Add(10, 20)No object needed
Non-static method in different namespaceHelper helper = new Helper();Requires object
Static call in non-static contextDone inside UseStaticMethod()Allowed
Non-static call in static contextDone inside CallNonStaticFromStatic()Allowed using object

Comments

Popular posts from this blog

Interview Tips: Dot NET Framework vs Net CORE

FREE Webinar: Run Your Own Independent DeepSeek LLM

ORACLE 11g: User Authentication System with Stored Procedure and SQL*Plus Integration