I've got a question about C#. I've seen a lot of projects with the two examples:
- The first one get an existing Order with Order o = new Order(1);
- The other get an existing Order with Order o = OrderManager.GetOrderById(1);
The first used an constructor the other an method by an other class. Is that the "programming-style" of a programmer or a C# rule?
I hope you understand what I tried to ask...
Regards,
Olaf
Om prakash SinghPosted Jun 30, 2011, 12:28 AM
It means you are creating a new memory space for object o of order type.
When you do Order o = OrderManager.GetOrderById(1);
It means that you are assigning reference to object o of type order which is return by GetOrderById fuction of class OrderManager.
This is not any rule of C# but it is your own way(logic) to retrive the value.
VulpesPosted Jun 29, 2011, 5:51 PM
The second line is returning a reference to an existing Order object by calling the method OrderManager.GetOrderById and passing it an argument of 1.
I would imagine that the Order objects are stored within the OrderManager class and have an Id property to uniquely identify them which is passed in the constructor.
So, it's not so much a matter of style or rule - it's a question of creating a new object or accessing an existing one that is stored in some collection class.
In C#, constructors always return a reference to a new object of the class in question.
Other methods may or may not return references to new or existing objects - it depends what they're designed to do.