Reputation: 1
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;
}
Upvotes: 0
Views: 294
Reputation: 42
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;
}
Upvotes: -1
Reputation: 218828
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;
Upvotes: 6