Search code examples
c#.netwinformsmemory-managementvariable-types

Does textbox save an all number text as a long or string?


I have a brief discussion with my teammate regarding this. He says, if I enter a number in textbox, and try to use the value later on using textbox.text or val(textbox.text), I will not need to parse the value to integer. According to him, if the text attribute value is all number, you can directly get the value as integer, instead of string.

So, if I have textBox1.Text = "12345", then next time, if I use, intABC = textBox1.Text, it will not throw an error. Is it right? Does C# or other .Net language does this implicit conversion? Also, will the code store "12345" as string or integer? And how much memory will this value take, 5bytes for 5 characters or 2bytes for an integer?


Solution

  • TextBox.Text keeps the text as a simple string, it doesn't care about the real "meaning" of the string.

    Then, if you want to have your number back, you need to parse the string, hence neither implicit nor explicit cast to int is allowed (or better, it will throw an exception if you do it...).

    About the size, that text is stored as an UNICODE (UTF-16) string, hence from 2 to 4 bytes per character (depending on the character).

    You can easily measure the size (just the size of the string, without the overhead due to reference size etc.) using the following code:

    int numBytes = Encoding.Unicode.GetByteCount(stringToMeasure);
    

    To find more info about strings, unicode and encodings have a look here, here or here .