Reputation: 33
public class Unit
{
public int UnitId { get; set; }
public Engine EngineStuff { get; set; }
}
public class Engine
{
public int PS { get; set; }
public int MaxSpeed { get; set; }
}
var unit = new Unit();
unit.UnitId = 3; //OK because Unit-constructor was called
unit.EngineStuff.PS = 200; //error, because EngineStuff-constructor obviously wasn't called.
How can this "inner" constructor be called? I thought it initializes it automatically?
How can I simply assign a value to the property "EngineStuff.PS"?
Upvotes: 3
Views: 75
Reputation: 3902
Addition to other answers, you can define a getter property to create the instance when you need it first time:
public class Unit
{
public int UnitId { get; set; }
private Engine engineStuff;
public Engine EngineStuff
{
get
{
if (engineStuff == null) engineStuff = new EngineStuff();
return engineStuff;
}
}
}
Upvotes: 0
Reputation: 77926
No, you need to set it explicitly like below cause EngineStuff
is of type Engine
and so you will have instantiate it first before accessing any of it's member.
unit.EngineStuff = new Engine { PS = 10, MaxSpeed = 2000 };
(OR) you can change your Unit
class to have EngineStuff
as a getter property and have the instance created there like below
public Engine EngineStuff
{
get
{
return new Engine();
}
}
Then you can access it
var unit = new Unit();
unit.UnitId = 3;
unit.EngineStuff.PS = 100;
Upvotes: 2
Reputation: 493
Simply you need to initialize EngineStuff
in either Unit
constructor or just before using it.
public class Unit
{
public Unit()
{
EngineStuff = new Engine();
}
public int UnitId { get; set; }
public Engine EngineStuff { get; set; }
}
Or :
var unit = new Unit();
unit.UnitId = 3;
unit.EngineStuff = new Engine():
unit.EngineStuff.PS = 200;
Upvotes: 4
Reputation: 100358
You have to instantiate object's properties explicitly:
public class Unit
{
public Unit()
{
EngineStuff = new Engine();
}
}
Or if you want to manually control when to instantiate:
var unit = new Unit();
unit.UnitId = 3;
unit.EngineStuff = new Engine();
unit.EngineStuff.PS = 200;
or simpler:
var unit = new Unit { UnitId = 3 };
unit.EngineStuff = new Engine { PS = 200 };
Upvotes: 4
Reputation: 312129
EngineStuff
is just a reference, you need to set its value to an Engine
object that you create, either in the Unit
constructor, a property initializer, or plain code.
So either:
// Constructor
public class Unit
{
public Unit() { EngineStuff = new Engine(); }
public int UnitId { get; set; }
public Engine EngineStuff { get; set; }
}
Or
// Property initializer
var unit = new Unit
{
UnitId = 3,
EngineStuff = new Engine { PS = 200 }
};
Or
// Plain code
var unit = new Unit();
unit.UnitId = 3;
unit.EngineStuff = new Engine { PS = 200 };
Upvotes: 2