G
Guest
I have just come across a real life example in which the C# syntax for
calling constructors from within other constructors is rather inconvenient.
Imagine a class with a default constructor and another constructor that takes
a parameter:
class MyClass
{
public MyClass()
{
}
public MyClass(int a)
{
}
}
In cases like these, the default constructor will usually call the other
constructor with a default value for the missing parameter, e.g.:
class MyClass
{
public MyClass() : this(100)
{
}
...
}
However, what happens if the default value of that parameter has to be
computed in a more complex way? In Java, it is as simple as doing your
calculations and then calling the second constructor:
public MyClass()
{
int b;
// do some calculations here
this(b);
}
After a lot of fiddling around, I figured out you can do something like this
in C# by implementing a static method and calling it during the constructor
chaining:
class MyClass
{
static int CalculateDefault()
{
int b;
// do some calculations
return b;
}
public MyClass(): this(CalculateDefault())
{
}
public MyClass(int a)
{
...
}
}
Needless to say, the elegance and readibility of this roundabout solution is
debatable, especially when you have more than one parameter without a
constant default value. Is there any reason why C# was designed this way?
Regards,
Daniel
calling constructors from within other constructors is rather inconvenient.
Imagine a class with a default constructor and another constructor that takes
a parameter:
class MyClass
{
public MyClass()
{
}
public MyClass(int a)
{
}
}
In cases like these, the default constructor will usually call the other
constructor with a default value for the missing parameter, e.g.:
class MyClass
{
public MyClass() : this(100)
{
}
...
}
However, what happens if the default value of that parameter has to be
computed in a more complex way? In Java, it is as simple as doing your
calculations and then calling the second constructor:
public MyClass()
{
int b;
// do some calculations here
this(b);
}
After a lot of fiddling around, I figured out you can do something like this
in C# by implementing a static method and calling it during the constructor
chaining:
class MyClass
{
static int CalculateDefault()
{
int b;
// do some calculations
return b;
}
public MyClass(): this(CalculateDefault())
{
}
public MyClass(int a)
{
...
}
}
Needless to say, the elegance and readibility of this roundabout solution is
debatable, especially when you have more than one parameter without a
constant default value. Is there any reason why C# was designed this way?
Regards,
Daniel