C# Constructors

mtwilson

New member
Joined
Aug 12, 2004
Messages
2
I am probably just be being a bit stupid but...
Code:
public MyClass( string s) : this( s, true )
public MyClass( string s, bool b )
{
     ...
}
That works fine, but what if I want to alter the string in the string in the first constructor before passing it on to the second?
Code:
public MyClass( string s)
{
    this( s + "muh", true);
}
public MyClass( string s, bool b )
{
     ...
}
That obviously doesnt work and I have tried other things so what is the solution? Unless moving the shared code into a seperate method is the only way.

Thanks

-Martin
 
mtwilson said:
That obviously doesnt work and I have tried other things so what is the solution? Unless moving the shared code into a seperate method is the only way.

Thanks

-Martin
I believe so. . .

I am wondering if swithcing the hierarchy around might be appropriate . . .
PHP:
public class MyClass
{
  string _s;
  public MyClass(string s, bool b):this(s)
  {
	  // do something based on b and/or s here 
  }
  
  public MyClass(string s)
  {
	// default s handling
  }
}
or a polymorphic hierarchy -

PHP:
public class MyClass
{
  protected string _s;
  protected virtual void Manipulate(ref string s)
  {
	  // default does nothing to s
  }
 
  public MyClass(string s, bool b)
  {
	  Manipulate(s);
	 _s = s;
  }
}
 
public class MyChildClass:MyClass
{
  protected override void Manipulate(ref string s)
  {
	  s += ": Manipulated";
  }
 
  public MyChildClass(string s):base(s,true)
  {
  }
}
 
If its as simple as appending a string, you can append it in the first example:
C#:
public MyClass( string s) : this( s + "muh", true )

But why would you be altering the string that the caller is passing in? Why not alter it in the "real" constructor? If its meant to be a flag, maybe you need yet another constructor to pass in what you really want...?

-ner
 
Back
Top