Calling overloaded constructor with values inside another constructor

  • Thread starter Thread starter Tristan
  • Start date Start date
T

Tristan

Hi,

I am trying to call an overloaded constructor from within an another
one with parameters that have to be processed inside the constructor.
Therfore I can't use the Constructor() : Constructor(params) type of
syntax. I think the code below, explains better what I'm trying to do.

Class AClass
{
AClass(string fileName)
{ }

AClass(string key)
{
// Do some special processing on key to get a fileName

// Here I want to call AClass(fileName) but how!!!!
}
}

I suspect this isn't possible and I just have to define some private
method that can get called by both constructors?

Any help appreciated.

Tristan.
 
Tristan said:
I am trying to call an overloaded constructor from within an another
one with parameters that have to be processed inside the constructor.
Therfore I can't use the Constructor() : Constructor(params) type of
syntax. I think the code below, explains better what I'm trying to do.

Class AClass
{
AClass(string fileName)
{ }

AClass(string key)
{
// Do some special processing on key to get a fileName

// Here I want to call AClass(fileName) but how!!!!
}
}

I suspect this isn't possible and I just have to define some private
method that can get called by both constructors?

Well, the first problem is that both of those constructors have the
same signature. However, once you've got rid of that, the way to
proceed is:

AClass (string key) : this (KeyToFilename(key))
{
}

// FileInfo used here as example
static FileInfo KeyToFilename(string key)
{
....
}
 
Hi Tristan,
Hi,

I am trying to call an overloaded constructor from within an another
one with parameters that have to be processed inside the constructor.
Therfore I can't use the Constructor() : Constructor(params) type of
syntax. I think the code below, explains better what I'm trying to do.

Class AClass
{
AClass(string fileName)
{ }

AClass(string key)
{
// Do some special processing on key to get a fileName

// Here I want to call AClass(fileName) but how!!!!
}
}

I suspect this isn't possible and I just have to define some private
method that can get called by both constructors?

It's impossible to define the same constructor second time.
Constructor/method parameters are identified by types (not by names).

If You want to create second constructor try this:

AClass(object key)
: this(key.ToString())
{
// and other stuff
}

Regards

Marcin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top