Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat is the best way to create a object in C# that will be re-used
    text
    copied!<p>I've the following class</p> <pre><code>public class Car { public int Id {get;set;} public string Name {get;set;} public bool Enabled {get;set;} public Car() { this.Enabled = false; } } </code></pre> <p>In my code I can create the object like below and set some properties.</p> <pre><code>Car oCar = new Car(); oCar.Id = 1; oCar.Name = "FastCar"; </code></pre> <p>I then have a separate function like below</p> <pre><code>public static Car MyCarTest() { //do some logic.... Car oCar = new Car(); oCar.Id = 1; oCar.Name = "Very FastCar"; oCar.Enabled = true; return oCar; } </code></pre> <p>If I call the same code as below, followed by the function;</p> <pre><code>Car oCar = new Car(); oCar.Id = 1; oCar.Name = "FastCar"; oCar = MyCarTest(); </code></pre> <p>On calling the function at this point it will create a new object of type Car and will assign the name as 'Very FastCar' and Enabled set to true; The Function returns a new Car() of which is assigned to the initial Car object that was created.</p> <ul> <li>EDIT *</li> </ul> <p>My question is, what is the proper way to create a object, set some properties values, and then later in your code, your conditional check means that the original object and property values that were set, will be overwritten by a new instance of the object like;</p> <pre><code>Car oCar = new Car(); oCar.Id = 1; oCar.Name = "FastCar"; Car oCar1 = new Car(); oCar.Id = 1; oCar.Name = "Very FastCar"; oCar.Enabled = true; oCar = oCar1 </code></pre> <p>Is this the preferred way ?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload