Can I call a overloaded constructor from another constructor of the same class in C#?
views:
3616answers:
4EDIT: According to the comments on the original post this is a C# question.
Short answer: yes, using the this
keyword.
Long answer: yes, using the this
keyword, and here's an example.
class MyClass
{
private object someData;
public MyClass(object data)
{
this.someData = data;
}
public MyClass() : this(new object())
{
// Calls the previous constructor with a new object,
// setting someData to that object
}
}
No, You can't do that, the only place you can call the constructor from another constructor in C# is immediately after ":" after the constructor. for example
class foo
{
public foo(){}
public foo(string s ) { }
public foo (string s1, string s2) : this(s1) {....}
}
In C# it is not possible to call another constructor from inside the method body. You can call a base constructor this way: foo(args):base() as pointed out yourself. You can also call another constructor in the same class: foo(args):this().
When you want to do something before calling a base constructor, it seems the construction of the base is class is dependant of some external things. If so, you should through arguments of the base constructor, not by setting properties of the base class or something like that
If you mean if you can do ctor chaining in C#, the answer is yes. The question has already been asked.
However it seems from the comments, it seems what you really intend to ask is
'Can I call an overloaded constructor from within another constructor with pre/post processing?'
Although C# doesn't have the syntax to do this, you could do this with a common initialization function (like you would do in C++ which doesn't support ctor chaining)
class A
{
//ctor chaining
public A():this(0)
{ Console.WriteLine("default ctor"); }
public A(int i)
{ Init(i); }
// what you want
public A(string s)
{
Console.WriteLine("string ctor overload" );
Console.WriteLine("pre-processing" );
Init(Int32.Parse(s));
Console.WriteLine("post-processing" );
}
private void Init(int i)
{
Console.WriteLine("int ctor {0}", i);
}
}