开发者

When is it necessary to convert data types in Visual Basic 2010

Visual Basic 2010 (Express). I can best give this by example...

If I take a string from a textbox and assign it to an integer variable, I'm under the impression that you're supposed to use CInt to explicitly convert the contents to an integer.

intMyCount = CInt(txtUserInput.Text)

However, if I don't do that, it st开发者_JAVA百科ill seems to work. Similarly, if I have an integer and concatenate it into a label's text property, it still works:

lblResults.Text = intMyCount & " number of times."

rather than using intMyCount.ToString.

Why does it work? Is VB doing implicit conversions when possible? Are there examples where not explicitly converting with .ToString or using CInt would cause unexpected results?


This is done using late-binding, and it's dangerous because if the conversion ever fails (and there's lots of cases where your first example could fail) it ends up in an exception at runtime. To get the compiler to enforce safer casting, turn Option Strict On.

Additionally, most of the time you don't want to use CInt() to convert your string to int. Instead, prefer Integer.Parse() or Integer.TryParse().


Some languages handle string concatenation easily like this for the non-casting to string. Some also handle non-casting to numeric types to do calculations. Some languages don't handle it at all. However as a best-practice, I would always cast the variable to the type you want to avoid issues with improper input types.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜