About constuctor arguments

  • Thread starter Thread starter Sam Sungshik Kong
  • Start date Start date
S

Sam Sungshik Kong

Hello!

Here's a simple class.

class C
{
public int Num;
public C(int i)
{
Num = i;
}
public C(string s): this(int.Parse(s))
{
}
}

When I create an object..

C o = new C("1"); //this is ok.
C o = new C("a"); //this causes an error, of course.

I want to have some exception handling mechanism for the argument validation
in the class.
What's the common practice for such a situation?

Thanks.

Sam
 
Sam Sungshik Kong said:
Hello!

Here's a simple class.

class C
{
public int Num;
public C(int i)
{
Num = i;
}
public C(string s): this(int.Parse(s))
{
}
}

When I create an object..

C o = new C("1"); //this is ok.
C o = new C("a"); //this causes an error, of course.

I want to have some exception handling mechanism for the argument
validation
in the class.
What's the common practice for such a situation?

In general, when you need to do something to a constructor argument, use a
private static function:

class C
{
public int Num;
public C(int i)
{
Num = i;
}
static int Parse(string s)
{
//validate s and throw an exception
return int.Parse(s);
}
public C(string s): this(Parse(s))
{
}
}

David
 
Sam,

If you want to have some sort of exception handling, you would have to
define a static method somewhere and then call that in the call to the other
constructor, like so:

private static int ValidateStringConstructorArgument(string s)
{
// Do something here, but return an int to pass to the overload of C
}

public C(string s) : this(ValidateStringConstructorArgument(s))
{}

Hope this helps.
 
Back
Top