Get Help:Ask a Question in our Forums|Report a Bug|More Help Resources
Last post Oct 25, 2011 10:27 AM by adeelehsan
Oct 25, 2011 09:35 AM|LINK
I have a very basic doubt and would be great if someone clears this up for me.
private int x;
public int method()
static void main(string args)
var x=new class().method();
Say, i have a simple class and code inside my main method as shown below.
In my first line, i am saying new class.method
In the second line i say the same but assign it to a var and print it. As expected i get 10 as o/p.
My question is, what is the new operator doing here, and how am i accessing method as a static method?
I have come across creating instances of classes using new operator, but what is happening here?
Oct 25, 2011 09:58 AM|LINK
You are not accessing the method as static method.
new class().Method() --> Creates an object and then call the metod
Class.Method() --> this is how to call static method
Oct 25, 2011 10:14 AM|LINK
new class().method() creates an object of the class.
If i use var x = new class.method(), x is holding the instance of the class correct? So its saving me an extra line by doing
var x = new class()
Is my understanding correct?
Also if i just say new class().method(); what is the purpose of this statement?
Oct 25, 2011 10:27 AM|LINK
Well, yes u are right. You are saving an extra line. But you are creating an anonymous object which will not be available on the next line.
So new Class().Method() is calling the Method but not creating a named object for the class. But if you say:
var x = new Class()
Then x is a named reference pointing to the object of the class and it can be used later within its scope to access other parts of the class.