Just like the title says.
I\'ve tried doing str.Replace(\"\",\"0\");
but it gave me error because oldValue
has zero length.
Is it possi
It sounds like your best option would be int.TryParse
, if you encounter a string that can't be set to a valid value, it will set it to the default value for an integer (0) as well as returning a boolean so you can know this has happened.
int myInt;
if(!int.TryParse(myStringVariable, out myInt))
{
//Invalid integer you can put something here if you like but not needed
//myInt has been set to zero
}
//The same code without the if statement, still sets myInt
int.TryParse(myStringVariable, out myInt);
If you know that str is empty then you may use star="a" If you want to check then write statement in if condition.
String.Replace takes two string arguments oldValue and newValue. You specified the newValue 0 however an empty string is not legal for the oldValue.
try below code :-
str.Replace(" ","0");
or you can just assign "0" to emptry string as below :-
if(str == string.Empty)
{
str = "0";
}
or making it simple :-
String.IsNullOrWhiteSpace(str) ? "0" : str;
It is not possible to replace string.Empty by "0". It will throw ArgumentException.
An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll.
Additional information: String cannot be of zero length.
You can try following code:
if(retString == string.Empty)
{
retString = "0";
}
Try This...
public string Method1()
{
string retString = string.Empty;
//Do Something
return string.IsNullOrEmpty(retString)?"0":retString;
}
If you want to check if the value is empty and then set the value to zero, otherwise use the default value you can use an inline if like so:
return string.IsNullOrWhiteSpace(retString ) ? "0" : retString;