Convert String.Empty to Nothing / Null

Is there any .Net function. I think if not, I have to make my own method.

The fact is that I have a function. It takes integers. If you pass an integer 0 or a zero value, it will still work. The problem is that the value of the empty text field is the value of String.Empty.

I do not want to use if's. I mean, it can, but much nicer, if I can simply name my function as follows

MyFunction (txtTextbox.Text)

But this will not work, because it cannot convert string.empty to an integer.

+3
source share
6 answers

, :

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

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

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

, , , int.Parse int.TryParse ?

+3

, , . null , - . - , , . NumTextBox, TextBox , , Text . , .

0

   Sub MyFunction(ByVal Param1Integer as Integer)
     ' Do Something
   End Sub

   Sub MyFunction(ByVal Param1String as String)
     MyFunction(Val(Param1String))
   End Sub

It is assumed that the empty string matches 0.

0
source

Have you studied the use of NumericUpDown (spin control)? It has a member .Value (always a valid Integer!) Instead of converting from String. You can limit the upper and lower values, as well as set a default value.

0
source

I would just use the built-in IF (VB) statement:

MyFunction(IIf(txtTextBox.Text Is Nothing, "", txtTextBox.Text))
0
source

Source: https://habr.com/ru/post/1733983/


All Articles