views:

156

answers:

1

This is a really simple question and I'm suprised I have to ask it but...

How does one declare a readonly local variable in VB.Net?

Java and C++ have final/const local variables so I'm sure VB.Net must have them, but I just can't find the syntax for it.

+4  A: 

Unfortunately, VB.NET only supports readonly fields not readonly locals. VB.NET does not have anything like C++'s const modifier to mark a variable as readonly.

Depending on the type of the variable, the Const modifier might do the job but it doesn't mean the same thing as C++'s const. In VB.NET, Const is simply a variable whose value is known at compilation time, thus allowing the compiler to replace all usages of that variable in the source code with the value itself.

While the compiler will prevent you from modifying a Const variable you are severely limited in your options for the types that you can mark as Const since most types cannot provide a known value at compilation time.

Andrew Hare
Are you serious? The inferior Java has something .Net doesn't have? Wow! I'm a little shocked that such a massive oversight slipped through
mcjabberz
I too would like to see this concept. However I would actually rather _all_ locals be implicitly readonly and only through a special modifier (like F#'s `mutable`) can a variable be changed after intialization.
Andrew Hare