Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning an alternative value if a string is not found in a string-returning method

Tags:

string

c#

return

I have a method which returns a string. It can be in normal operating conditions that a blank string or null is returned. However, is it a good coding practise to return null or "" from this method?

like image 707
GurdeepS Avatar asked Jun 08 '26 12:06

GurdeepS


2 Answers

Yes, in that situations I prefer returning null to show that string is not found. Empty string has usually used for showing empty result.

Alternative way is to throw some Exception, but as programmer I don't find usable to work with Exceptions. Returning null is much better.

like image 111
Chuck Norris Avatar answered Jun 11 '26 01:06

Chuck Norris


There is a semantic difference between null and the empty string. One says "it is not defined for that input", the other says "the correct value for that input is the empty string".

Imagine you have written a compiler for a subset of C that allows for a main-function that returns nothing. Your compiler returns a string with some fantasy assembly language.

// Testcode 0
void main() {

For this you would return null, the code is not well-formed because of the missing closing brace (no, do not throw an exception, errors in user written code are expected). There is no valid output.

// Testcode 1
void main() { printf("hello!"); }

For this you would return "push 'hello!'\ncall printf"

// Testcode 2
void main() {}

For this you might return "", the code does nothing and returns nothing, but is valid.

like image 40
Sebastian Mach Avatar answered Jun 11 '26 01:06

Sebastian Mach