Click here to Skip to main content
15,904,497 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
correct way to create an object of the class Sample..

Sample s = new Sample();


or

Sample s;
s = new Sample();



is there any difference or advantages in the way we are creating object to the class...


thanks in advance...
Posted

AFAIK, there is no difference between the two.
On the first one, you just immediately instantiate it after you declare your object.
On the second one, you declare your object first, then you instantiate it on the next line.

I always use the second one ( which I really don't know why) maybe because you can instantiate it on which event you needed it to be instantiated. Example:
C#
Sample s;

private void btnClick_click (object sender, EventArgs e)
{
//you don't need the object here yet..
//add code here
}

private void btnSubmit_Click (object sender, EventArgs e)
{
//in this event you need to instantiate your object.
s = new Sample();
//add code here
}
 
Share this answer
 
Comments
crazie.coder 28-May-14 2:42am    
yes..always use second one
I use the first when I can; the second when I have to.

I would never do the second on consecutive lines like your example; there would always be something (usually scoping) to separate the statements.
 
Share this answer
 

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