Static Method from a Non-Static Method and Vice versa
✅ Calling a Static Method from a Non-Static Method
and
✅ Calling a Non-Static Method from a 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.csnamespace 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.csnamespace Utilities{ public class Helper { public string GetGreeting(string name) { return $"Hello, {name}!"; } }}
✅ Step 3: Main Program – Calling Methods in MainApp
// File: Program.csusing 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
Scenario | Example Used | Notes |
---|---|---|
Static method in a different namespace | Calculator.Add(10, 20) | No object needed |
Non-static method in a different namespace | Helper helper = new Helper(); | Requires object |
Static call in non-static context | Done inside UseStaticMethod() | Allowed |
Non-static call in static context | Done inside CallNonStaticFromStatic() | Allowed using object |
Comments
Post a Comment