Avatar of JRumana
JRumana
 asked on

C# main class instance

I have a doubt in the following code why we have to create the instance

of the same class like below

TestDelegateClass tdc = new TestDelegateClass();

in the given code.

My doubt is we have to create instance if there are two classes but here are having only one class
Please clarify me..



public delegate Boolean MyDelegate(Object sendingobj, Int32 x);
 
public class TestDelegateClass
{     
	Boolean MyFunction(Object sendingobj, Int32 x) 
	{           
		//Perform some processing           
		return (true);  
	}
	       
	public static void main(String [] args)
	{
		//Instantiate the delegate passing the method to invoke in its constructor
		MyDelegate mdg = new MyDelegate(MyFunction);
            
		// Construct an instance of this class
		TestDelegateClass tdc = new TestDelegateClass();
               
		// The following line will call MyFunction
		Boolean f = mdg(this, 1);
       
	}
}

Open in new window

C#Programming Languages-Other

Avatar of undefined
Last Comment
JRumana

8/22/2022 - Mon
CyrexCore2k

As I understand it, you're asking why you have to create an instance of the class when you already have one.

The answer is you don't already have an instance of the class. The static keyword modifying the main method allows the method to be called without instantiating the class. Static methods behave the same way no matter what class they're in. It's just a fancy way of organizing methods. Consider how the Math class has functions for Cos and Sin. You don't need to instantiate a new Math object in order to call these functions as they require no instance information to give you an appropriate result.

Hope that helps.
JRumana

ASKER
Ok... if i comment the line
   
//   TestDelegateClass tdc = new TestDelegateClass();

then the above program will work or not? please clarify me.
ASKER CERTIFIED SOLUTION
CyrexCore2k

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
JRumana

ASKER
Now i got it thanks for your help
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck