Can somebody explain what means : this(123)
in a constructor ?
public class MyObject
{
public MyObject(): this(123)
{
}
............
}
Can somebody explain what means : this(123)
in a constructor ?
public class MyObject
{
public MyObject(): this(123)
{
}
............
}
Because your class has another constructor which takes and int
as parameter.
public class MyObject
{
public MyObject()
: this(123)
{
}
public MyObject(int x) //something like this
{
}
}
See: Using Constructors (C# Programming Guide)
A constructor can invoke another constructor in the same object by using the
this
keyword.
This means, that you are calling another constructor with the fixed Value "123":
public class MyObject
{
public MyObject(): this(123)
{
}
public MyObject(int number)
{
}
}
Means: Whenever you call new MyObject()
, without any parameter, it equals the call to new MyObject(123);
this is used to call one constructor from another within the same class. Refer to this article for better understanding.
http://www.codeproject.com/Articles/7011/An-Intro-to-Constructors-in-C
You have another constructor that accepts an int (thought it could be long or double, or anything else that int can implicitly cast to)
public class MyObject
{
public MyObject(): this(123)
{
}
public MyObject(int num)
{
//do something with the num
}
}
That means "before you execute what between the curly brackets, execute the suitable Constructor with parameters 123
"
The syntax provided is used for "constructor chaining" whereby the specified constructor (which accepts an integer argument) is called before the body of the current constructor.