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.
Code consuming a ReadOnly property cannot set its value. But code that has access to the underlying storage can assign or change the value at any time. You can assign a value to a ReadOnly variable only in its declaration or in the constructor of a class or structure in which it is defined.
Read-only fields in visual basic can be created by using ReadOnly keyword. In visual basic, the read-only fields can be initialized either at the declaration or in a constructor. The read-only field values will be evaluated during the run time in visual basic.
You can use WriteOnly only at module level. This means the declaration context for a WriteOnly property must be a class, structure, or module, and cannot be a source file, namespace, or procedure. You can declare a property as WriteOnly , but not a variable.
To do this, you must declare the ReadOnly variable at class or structure level. In the constructor for that class or structure, compute the variable's fixed value, and assign it to the variable before returning from the constructor.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With