Convert String.Empty to Nothing/Null

Tomasi picture Tomasi · Feb 23, 2010 · Viewed 12.3k times · Source

Is there a .Net function that does that. I guess if there isn't i have to make my own method.

The thing is i have a function. It accepts integers. If you pass a 0 integer or a null value it still works. Problem is that the value of an empty textbox is a String.Empty value.

I don't want to use if's. I mean it could but its much nicer if i can just call my function like this

MyFunction(txtTextbox.Text)

But it won't work because it can't convert the string.empty to a integer.

Answer

Fitzchak Yitzchaki picture Fitzchak Yitzchaki · Feb 23, 2010

I guess you need:

if(string.IsNullOrEmpty(value)) value = null;

or

int MyFunction(string value)
 {
      if(string.IsNullOrEmpty(value)) return 0;

      int val = 0;
      int.TryParse(value, out val);
      return val;
 }