Exception

S

shapper

Hello,

I have a class with a function which returns a string.

However, at the same time I might need to return an error code
(integer).

I need to access this code after calling the function.

How can I do this? Maybe using exception some how?

Thanks,

Miguel
 
M

Mark Fitzpatrick

Miguel,
You could throw an exeption, but generally that's a bit more
expensive operation and you would have to guarantee being able to catch it
every time. Why not just use an output parameter on the function? This is
done a lot when you need to return more than one value. For example, look at
the int.TryParse() method. It returns a boolean value to say that the string
passed to it is a valid int, and then the second parameter returns an actual
integer value like so:
bool isInteger = false;
string myInt = "1";
int intValue = 0;
isInteger = int.TryParse(myInt, out intValue);
 
K

Karl Seguin [MVP]

The decision between output parameters vs exception isn't generally about
performance, it's about design. They each serve a diferent design.
Int32.TryParse uses an output parameter, and Int32.Parse uses an exception -
they both have different design/purpose.

You should use an exception if the "error code" occurs under truly
rare/unexpected/exceptional situations.

Karl
 

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

Members online

Forum statistics

Threads
473,790
Messages
2,569,637
Members
45,346
Latest member
EstebanCoa

Latest Threads

Top