I have a very basic doubt and would be great if someone clears this up for me.
public class.cs
{
private int x;
public int method()
{
return x=10;
}
}
static void main(string[] args)
{
new class().method();
var x=new class().method();
console.writeline(x.toString());
}
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?
praveen.8721
Member
78 Points
65 Posts
Doubt regarding new keyword
Oct 25, 2011 09:35 AM|LINK
I have a very basic doubt and would be great if someone clears this up for me.
public class.cs { private int x; public int method() { return x=10; } } static void main(string[] args) { new class().method(); var x=new class().method(); console.writeline(x.toString()); }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?
Praveen
Lateef045
Star
7813 Points
1541 Posts
Re: Doubt regarding new keyword
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
praveen.8721
Member
78 Points
65 Posts
Re: Doubt regarding new keyword
Oct 25, 2011 10:14 AM|LINK
Thanks.
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()
x.method()
Is my understanding correct?
Also if i just say new class().method(); what is the purpose of this statement?
Praveen
adeelehsan
All-Star
18265 Points
2731 Posts
Re: Doubt regarding new keyword
Oct 25, 2011 10:27 AM|LINK
Hi
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.
MCPD ASP.NET 4.0 and 3.5, MCTS WSS, MOSS, SharePoint 2010, MCT
Microsoft Community Contributor Award 2011