0

For a project I need to change a string affected to null or a white space to default. In my head this code makes sense but what am I missing? It just return a whitespace like it hasnt changed at all. I'm new to programming and I'm looking for help. Thank you :).

static void Main(string[] args)
    {
        string s = "";
        ValidateString(s);
        Console.WriteLine(s);

    }
    static string ValidateString(string s)
    {
        if (s == null || String.IsNullOrWhiteSpace(s))
            s = "défault";
        return s;
    }
  • Note: I found out I could just add a "ref". Isn't there an easier way to do it? – Edouard Frechette Mar 05 '19 at 23:04
  • Possible duplicate of [C# string reference type?](https://stackoverflow.com/questions/1096449/c-sharp-string-reference-type) – Blue Mar 05 '19 at 23:09
  • 1
    @FrankerZ surprisingly that (good) duplicate does not show how to actually deal with strings (so not hammering)... Maybe https://stackoverflow.com/questions/1948978/string-replace-or-other-string-modification-not-working would do better? – Alexei Levenkov Mar 05 '19 at 23:32
  • 1
    FYI, `IsNullOrWhiteSpace` returns `true` if the string is `null`, so you don't need `s == null` in addition to that. – Rufus L Mar 05 '19 at 23:41

2 Answers2

5

You're returning the value from the method, but you're not capturing that return value. Update the variable with the returned value:

string s = "";
s = ValidateString(s); // <--- here
Console.WriteLine(s);

Or, more simply:

Console.WriteLine(ValidateString(""));

Your method itself could also be simplified to:

return string.IsNullOrWhiteSpace(s) ? "défault" : s;
David
  • 208,112
  • 36
  • 198
  • 279
-1

s not change because you ignore the return value of the ValidateString method, change your code like below:

s= ValidateString(s);    

and the ValidateString can imporved like this:

static string ValidateString(string s)
{
    return string.IsNullOrWhiteSpace(s) ? "défault" : s;
}
Yu Jiaao
  • 4,444
  • 5
  • 44
  • 57
  • A good optimization of the method, but doesn't solve the problem. – David Mar 05 '19 at 23:18
  • Would be helpful if you added an explanation of what the OP was doing incorrectly, and how this solves the problem (code-only answers are often not as helpful without some description) – Rufus L Mar 05 '19 at 23:37