patterncsharpModerate
Truck class constructor
Viewed 0 times
classtruckconstructor
Problem
Is there a better way to pass variables into a class?
I have learned C# by error code and there has got to be a better way to do this. I am stuck on Framework 2.0.
public class Truck
{
private int _wheels;
private string _color;
private bool _loaded;
public int wheels { get { return _wheels; } }
public string color { get { return _color; } }
public bool loaded { get { return _loaded; } }
public Truck(int wheels, string color, bool loaded)
{
this._wheels = wheels;
this._color = color;
this._loaded = loaded;
}
}
Truck dumpTruck = new Truck(6, "yellow", false);I have learned C# by error code and there has got to be a better way to do this. I am stuck on Framework 2.0.
Solution
A few observations.
-
Properties should be PascalCase.
-
The
Now, to answer your question, you could use Automatic Properties, which would change your class to be something like:
As for your question of having a better way: the only other way to set them is to make the property's
-
Properties should be PascalCase.
public class Truck
{
// ...
public int Wheels { get {return _wheels; } }
// ...
}-
The
this keyword is not needed here. by having the '_' in front of your class variables, you are differentiating them from the local variables.Now, to answer your question, you could use Automatic Properties, which would change your class to be something like:
public class Truck
{
public int Wheels { get; private set; }
public string Color { get; private set; }
public bool Loaded { get; private set; }
public Truck(int wheels, string color, bool loaded)
{
Wheels = wheels;
Color = color;
Loaded = loaded;
}
}As for your question of having a better way: the only other way to set them is to make the property's
set method public and set them through that. Personally, I like passing them through the constructor better, it makes it easier to make the the class immutable.Code Snippets
public class Truck
{
// ...
public int Wheels { get {return _wheels; } }
// ...
}public class Truck
{
public int Wheels { get; private set; }
public string Color { get; private set; }
public bool Loaded { get; private set; }
public Truck(int wheels, string color, bool loaded)
{
Wheels = wheels;
Color = color;
Loaded = loaded;
}
}Context
StackExchange Code Review Q#44286, answer score: 10
Revisions (0)
No revisions yet.