C# Changing a constant
I have inherited a small windows form based program written in C# that uses a 'constant' (See below), I need to modify this program so 'PROPERTY_NAME' can be "jobs" and "careers".
private const string PROPERTY_NAME = "jobs";
I'm guessing a constant isn't designed to change so should I need to change this. The line above is set once at the top of a class file and then PROPERTY_NAME is used throughout that file.
On the main form I would like to add two radio buttons 1 called 'jobs' and one called 'careers' and then change the PROPERTY_NAME in the class file based on which is selected. Would I need to pass the radio but开发者_StackOverflow社区ton status to the method in the class file? I recall reading that I can't simply read the radio button value from the class file.
Many thanks for your advice.
Jane
My best (and simplest) guess (I could elaborate into cleaner things but this is just for speed) without seeing any other part of the code would be to remove the const
and add readonly
so PROPERTY_NAME
is just a plain old class member variable that cannot change outside of the constructor.
In the class's constructor, take in a string parameter, and have the code that creates an instance of this class pass in either "jobs" or "careers" (coming from the selected radio button probably) and set the PROPERTY_NAME
variable.
EDIT:
Like Sasha says, another way would be using an enum
but it depends what exactly is being done with PROPERTY_NAME
as to whether this is appropriate for your application.
If the quantity you are representing changes ever throughout the history of the universe then do not make it a constant. Constants are things like the number of eggs in a dozen or the atomic weight of lead. Things like version numbers or the current price of gold change over time and therefore are not constant. Only make actually constant values into constant fields. The compiler will treat constant fields as constant for all time, which can introduce semantic errors if they change.
make an enum (my preferred way) and make it a readonly property. Set this property in the constructor. It isn't changeable after creation and should do what you need.
-sa
You cannot make constant having two values. It looks like that you need to make a field storing current property name and use it allover your form. And you will be able to init such field from the radio button.
精彩评论