I'm new to C# and I'm trying to figure out the best way to test if a method returns correctly, ie; did the method get the information I wanted.
It's the types that are making this difficult. Is there a way that I can sometimes return bool and sometimes return something else?
In PHP I would create my function like this
function myFunc(){
//Do Stuff
if(/*whatever*/) return (string) "abcdefg";
return false; //otherwise it will just return false
}
Then call it like this to test if it worked or not
if(!$var=myFunc()) die("It Didn't Work");
echo $var;
But with C#, my function has to return a specified type, not a string or bool false if it didn't work out.
If in C# I have a method that returns IntPtr I could have it return (IntPtr) 0
instead of false, but this is messy and there's probably a better way of doing it.
Any Ideas? What's the standard and usual way of doing this in C#?
There are typically two approaches here:
The appropriate method depends on what this is doing. If the "false" case is really something that's exceptional and not the norm, raising an exception is an appropriate way of handling it.
If, however, you're doing something like parsing user input, where its common that you'll "fail", using the TryXXX approach is a good example. This would look like:
bool TryMyFunc(out string result)
{
if (...)
{
result = "abcdefg";
return true;
}
result = string.Empty;
return false;
}
This is how Int32.TryParse works in the framework, for example.
You can always return null.
string Foo()
{
if (!success) return null;
return "abcd";
}
You then check the call like that:
var tmp = Foo();
if (tmp == null) return -1;
// tmp is a string so do your work
The null return will only work with object, unfortunately you can't do that with an int. In that case throw an exception or use a nullable int:
int? Bar()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With