开发者

Immutable Dot Net strings

I usually define my string variables in vb.net as

Dim f_sName as string=String.Empty
f_sName = "foo"

Given the immutable nature of strings in .net, is there a better way to initialize strings and deal with the "Variable 'f_sName 开发者_C百科' is used before it has been assigned a value. A null reference exception could result at runtime." warning?

Also for classes that do not have constructors which accept no arguments such as System.Net.Sockets.NetworkStream, what is the best way to define and initialize a variable of that type?


This has nothing to do with the strings being immutable.

A better preferable pattern would be

 Dim f_sName as string = "Foo"

But it depends on the situation if you can use that.

Same for initializing with Nothing or Empty. If you want to catch errors early, then:

  1. just don't initialize at all. "Variable 'xxx' is used before it has been assigned a value" is your friend, not your enemy.
  2. Initialize with Nothing. It too might bring errors to light.
  3. Initialize with Empty (or just "", no difference).

And concerning classes like NetworkStream, same thing: don't create instance and don't declare variables until you need them. For a Disposable class like NetworkStream this means use a Using clause:

 Using fs As New NetworkStream(....)

 End Using

It is neither desirable nor useful to have 'fs' available outside that narrow scope.


Dim f_sName as String = Nothing

or

Dim f_sName As New String()

By the way: mixing mixedCase variable naming with underscores (as in f_sName) looks strange most of the time, what does this variable name stand for?


Initializing a string to null and to String.Empty are pretty much the same thing. Personally, I think setting it to string.empty really is the best way of handling it. Setting it to null will result in throwing null reference exceptions though where as setting it to String.Empty will not.

One can argue the merits of initializing it one of two ways, but optimization wise there is no discernible difference.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜