public class Car
{
public int Id {get;set;}
public string Name {get;set;}
public bool Enabled {get;set;}
public Car()
{
this.Enabled = false;
}
}
In my code I can create the object like below and set some properties.
Car oCar = new Car();
oCar.Id = 1;
oCar.Name = "FastCar";
I then have a separate function like below
public static Car MyCarTest()
{
//do some logic....
Car oCar = new Car();
oCar.Id = 1;
oCar.Name = "Very FastCar";
oCar.Enabled = true;
return oCar;
}
If I call the same code as below, followed by the function;
Car oCar = new Car();
oCar.Id = 1;
oCar.Name = "FastCar";
oCar = MyCarTest();
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.
EDIT *
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;
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
Is this the preferred way ?
Solution
In the example you're actually changing the originally created car:
Car oCar = new Car();
oCar.Id = 1;
oCar.Name = "FastCar";
when you call:
oCar = MyCarTest();
making the original creation moot. If you're wanting to build a method that returns a default object, then just do this:
var oCar = MyCarTest();
OTHER TIPS
Your call to MyCarTest is indeed overwriting your oCar variable, as Michael noted. That said, what you have here
public static Car MyCarTest()
{
//do some logic....
Car oCar = new Car();
oCar.Id = 1;
oCar.Name = "Very FastCar";
oCar.Enabled = true;
return oCar;
}
is usually referred to as
a factory function. If you need to create an object with the same basic properties again and again, this is absolutely a common way to do it.
In addition to:
Car oCar = new Car();
oCar.Id = 1;
oCar.Name = "FastCar";
you can also do:
Car oCar = new Car
{
Id = 1,
Name = "FastCar"
};
Whether one way or the other is the "normal" way of doing things is a moot point. Some may prefer one way over the other, but both are valid.