Hi,
an example,
class PositiveNumber
{
private int i;
public PositiveNumber(int i)
{
// let's check the arguments first
if (i < 0)
throw new InvalidArgumentException("i"); // let's pass some info
with the exception object
this.i = i;
}
}
now if you try to create a PositiveNumber with a negative value, an
exception is thrown. The constructor will (in that case) not run till it's
end. Instead, execution will resume at the first catch clause willing to
handle this kind of exception. You might need to read a bit about
exceptions.
an example,
PositiveNumber number;
try // there might go something wrong in the following code, so let's guard
it
{
number = new PositiveNumber(-1);
}
catch (InvalidArgumentException e) // only catching InvalidArgumentException
exceptions here
{
MessageBox.Show("invalid argument passed: " + e.Message);
// you can do whatever you like here, like creating a default value
number = PositiveNumber(0);
}
Writing the evaluation code within the constructor keeps everything clean
(that's what object-oriented programming is all about).
One possible downside: objects are always created, that is, allocated on the
gc heap, even with invalid arguments, but they will be discarded immediately
because of the exception thrown. Usually nothing to worry about.
Exceptions are supposed not to happen frequently. That's why they are
called exceptions. Everything will be fine, except ...
Hope this helped,
Greetings,
Bram.
"Adie" <ar*******@h-o-t-m-a-i-l.com> wrote in message
news:71******************************@news.teranew s.com...
Adie wrote:Bram wrote:
Hi,
you could validate the inputs within the constructor(s) and throw an
exception when something is wrong or missing.
You mean I can pass an exception back from a constructor?
Right, think I know what youre getting at:
http://msdn.microsoft.com/library/de...Components.asp
might do the trick -- I think?!?!
We'll see.