Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Readonly local variable in VB.Net

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.

like image 218
mcjabberz Avatar asked Sep 11 '09 19:09

mcjabberz


People also ask

What is ReadOnly in VB net?

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.

How set ReadOnly property in VB net?

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.

How can you make a property write only?

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.

How to make a variable not change c#?

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.


1 Answers

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.

like image 148
Andrew Hare Avatar answered Nov 14 '22 07:11

Andrew Hare