Click here to Skip to main content
15,919,778 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I need to call the method without creating the object.

What I have tried:

I have two files A1.cs and A2.cs,

class A1
{
In this i am loading the A2,After Again come back to A1 .Now Page is loading completely.

.....
.....
X();

}
class A2
{}

Now my requirement is i need to call the X() method from A2. Without creating the object
Posted
Updated 28-Aug-18 19:50pm

1 solution

You can only call a method from a class without an instance of that class if the method is declared static i.e. it does not need to access any instance based information in order to work.

Think of cars for a moment: a car has two properties: a colour and a number of wheels. Let's write a quick method to fetch them.
The colour of a car obviously depend on the specific car you refer to: "my car" will be black, "your car" might be blue, "that car" could be green now, and refer to a yellow car in a minute. So GetColour requires access to instance based information:
C#
public Color GetColour()
   {
   return this.Colour;
   }
And we need an instance of the car to use it:
C#
Car myCar == new Mercedes("A180", Color.Black);
Car yourCar = new BMW("6 Series", Colour.Blue);
Console.WriteLine("My car is {0}", myCar.GetColour());
Console.WriteLine("Your car is {0}", yourCar.GetColour());
But the number of wheels is a constant - it's always four (because if it had two it would be a motorcycle!) So we don't need access to any instance based information, and it can be a static method:
C#
public static int GetNumberOfWheels()
   {
   return 4;
   }
And we use it without an instance by using the class name as a prefix:
C#
Console.WriteLine("My car has {0} wheels", Car.GetNumberOfWheels());
Console.WriteLine("Your car has {0} wheels", Car.GetNumberOfWheels());


So provided X does not need to access any instance information, you can declare it as static and call it via the class name:
C#
A2.X();
But if it needs to use this at all - explicitly or implicitly - it can't be static because that is the accessor for instance based information.
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900