I was reading a book about csharp called
"Pro C# 2010 and .NET 4 Platform"
I came across a piece of code that i dont understand. the book doesnt explain it and i cant continue knowing there is a piece of info that i didnt understand.
I would really appreciate if someone could help me understand the code on the line number 19
1> public enum PointColor
2> { LightBlue, BloodRed, Gold }
3> class Point
4> {
5> public int X { get; set; }
6> public int Y { get; set; }
7> public PointColor Color{ get; set; }
8> public Point(int xVal, int yVal)
9> {
10> X = xVal;
11> Y = yVal;
12> Color = PointColor.Gold;
13> }
14> public Point(PointColor ptColor)
15> {
16> Color = ptColor;
17> }
18> public Point()
19> : this(PointColor.BloodRed){ } <<<<<<<<<<<<<< I need to understand this line
20> public void DisplayStats()
21> {
22> Console.WriteLine("[{0}, {1}]", X, Y);
23> Console.WriteLine("Point is {0}", Color);
Assume you have two constructors, one which takes and argument and one which does not. Your simple constructor (the one that does not take an argument) can just call the complex constructor and provide a default value. This allows you to keep all of your constructor logic in one place instead of duplicating code.
Code:
class MyClass
{
private Rectangle _rect;
public MyClass() : this( new Rectangle(0, 0, 10 10 ) ) { } // calls MyClass(Rectangle rect)
public MyClass( Rectangle rect )
{
_rect = rect;
}
}
Instead of...
Code:
class MyClass
{
private Rectangle _rect;
public MyClass()
{
_rect = new Rectangle(0, 0, 10 10 );
}
public MyClass( Rectangle rect )
{
_rect = rect;
}
}
I know that may seem trivial, but a meaningful constructor will do more than that and chaining them keeps your code clean and maintainable.
Bookmarks