I am willing to check if a variable is const or not. How can I do it? I Googled a lot and couldn't find a anwser.
I have a line of code: public const string xxx, in a class, and I want to check whether xxx is const or not in another class.
The const keyword stands for constant. It is a variable qualifier that modifies the behavior of the variable, making a variable "read-only". This means that the variable can be used just as any other variable of its type, but its value cannot be changed.
The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable—just that the variable identifier cannot be reassigned. For instance, in the case where the content is an object, this means the object's contents (e.g., its properties) can be altered.
Variables can be declared using const similar to var or let declarations. The const makes a variable a constant where its value cannot be changed. Const variables have the same scoping rules as let variables.
A constant does not change its value over time. A variable, on the other hand, changes its value dependent on the equation. Constants are usually written in numbers.
How to check a variable is const or not?
No variables are consts. "Variable" and "const" are opposites: a variable is a storage location which can change. A constant is a value which cannot.
Can you say why you are asking the question? Likely you are going off on some wrong path; say what your real problem is and you'll have a better chance of getting a solution.
UPDATE: The question has been clarified. The question really is
How can I tell if a member of a class or struct is a variable or a constant?
You can use reflection to tell that, like this:
Type
of the class or struct via whatever technique you like.FieldInfo
of the member of the type using GetFields
, if you do not know the name, or GetField
if you do.FieldInfo
of a constant will have IsLiteral
set to true and IsInitOnly
set to false.Be careful because the rules are a little bit tricky. Remember that there are three things: normal variables, readonly variables, and constants. Variables are storage locations which can change. Constants are values which cannot. But readonly variables are variables that can change only in the constructor or initializer, and are therefore sometimes classified as variables and sometimes classified as values, but never classified as constants.
Again, it would be great if you said why you were doing this, because there might be a better solution to your real problem.
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