Click here to Skip to main content
15,890,579 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi everyone!
What's difference between

C#
Person p = new Person();
p = PersonService.GetByID(1);


and

C#
Person p = PersonService.GetByID(1);


I don't think they difference. But someone say that they difference. I don't understand what they say. Please explain to me.
Posted
Comments
Vitaly Tomilov 30-Jun-12 19:03pm    
Impossible to answer until we know what PersonService.GetByID(int) does.
ngotandatnnst 30-Jun-12 23:53pm    
Thanks for your reading my question.
GetByID take a personID and return a person
Sergey Alexandrovich Kryukov 1-Jul-12 3:11am    
No, you did not answer Vitaly's question. What it does, internally?
--SA

1 solution

The difference is in how many instances you are creating. In the first example, you are creating a new person instance. Then you are overwriting that instance with a new instance that is loaded by the specified ID. In the second example, you are loading the variable with the instance created by the specified ID. The difference is in that first instantiation. The second example is doing one instantiation versus two instantiations of the first example.

In my opinion, I would recommend doing it the second way if you are doing the two statements together. However, if you have lines of code between line one and line two of the first example, I recommend doing it that way. The reason is because then you will not get an "object not set to an instance of the object" error if you try to use the variable before you instantiate it.
 
Share this answer
 
Comments
Vitaly Tomilov 1-Jul-12 0:40am    
+5;

Not that it may mean anything to the person who asked the question :) but the first one is standard instantiation, while the second one is instantiation through factory ;)

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