Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

method return types

Tags:

c#

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#?

like image 262
Drahcir Avatar asked Dec 16 '22 07:12

Drahcir


2 Answers

There are typically two approaches here:

  1. Use Exceptions
  2. Use the TryXXX approach.

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.

like image 63
Reed Copsey Avatar answered Dec 30 '22 21:12

Reed Copsey


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()
like image 40
Beku Avatar answered Dec 30 '22 21:12

Beku