I would like to know how to declare a "global" variable for a class. That is I want that this variable is available everywhere just in this class and not in the other classes.
What is the best form to declare them? or when do I use each of these forms?
I would like to have it OO.
1st Form:
enter code here
private const string _Column1= "Names";
private const string _Column2= "Numbers";
private const string _Column3= "Alarms";
2nd Form:
private enum enumColumnNames
{
Names, // integer value = 0
Numbers, // 1
Alarms, // 2
};
3rd Form:
internal sealed class clsColumnNames
{
public static readonly clsColumnNames Column1 = new clsColumnNames("Names");
public static readonly clsColumnNames Column2 = new clsColumnNames("Numbers");
public static readonly clsColumnNames Column3 = new clsColumnNames("Alarms");
private clsColumnNames(string value)
{ Value = value;
}
public string Value { get; private set; }
}
4th Form:
internal sealed class clsColumnNames
{
public static readonly string Column1 = "Names";
public static readonly string Column2= "Numbers";
public static readonly string Column3= "Alarms";
}
Thanks!
Cis
private enum enumColumnNames
{
Names, // integer value = 0
Numbers, // 1
Alarms, // 2
};
And as long as the string value is equal to the enum name you can use
enumColumnNames.Names.ToString() will produce "Names"
static class ColumnNames
{
public const string Names = "Names";
public const string Number = "Numbers";
public const string Alarms = "Alarms";
}
Since these are constants, I would recommend the enum approach. As mentioned by Amorphis, this will aloow you to get the literal value viw .ToString(). This also allows you to pass around your strings as a parameter boxed to the given values by using the enum type as a parameter, rather than a string which may or may not be one of the given values. There are some ways around this (such as converting an out-of-range int) but it's still less error-prone than passing raw strings everywhere.
Not also, however, that whenever you have front-facing text, you should use a Resource (.resx), because this allows you to adjust how the strings show up depending on the language settings of the machine running your code. If any of these strings are ever to be seen by a user, use resources!
The 1st form is the best for the following reasons:
Simplest
Less typing
The 2nd form will just result in lots of needless extra code/typing (i.e., enumColumnNames.Names.ToString(), just to get the value of your variable. I've already worn my fingers out just typing that once).
For the 3rd form, let's break it down:
Making the class internal isn't really changing anything since your variables are private
Making the class sealed just means the class cannot be inherited from; again, this is not changing anything since your variables are private
Making your variables static just means that they won't show up in an object of the class; again, not really doing anything
Making your variables readonly just means that they can only be set in a constructor
There is no point in having a property for a variable that you intend to be constant; Properties are generally used to make sure that a variable is being set/gotten properly
And for the 4th form, same gripes as with the 3rd, just minus the last gripe.
EDIT:
Since these particular variables you are asking about are supposed to be column names, I would actually recommend Amorphis' answer (sorry Amorphis, I don't have enough rep to upvote your answer just yet). If your global variables are unrelated to each other (i.e., a variable for the name of a webpage vs. a variable for the number of characters allowed in a text field are nice and dissimilar), then you ought to use the first form.
Related
Is there any difference between the following?
class C
{
// One:
public static readonly int ValueAsAMember = 42;
// Two:
public static int ValueAsAProperty { get { return 42; } }
}
I'm used to writing constants the first way (unless they're private/internal, in which case I use the const keyword), but I recently saw the second form.
Is there any advantage one way over the other in terms of readability, convention, performance, or anything else?
You have three choices:
public static readonly int Value = 42;
public static int Value { get { return 42; } }
public const int Value = 42;
Choose static readonly if the value will not change at runtime but might change in future versions of your code.
Choose a property if the value might change at runtime. Of course it won't change if you use the given code.
Choose const if the value is really a constant that will not even change in future versions (something like Math.PI or int.MinValue). And of course the use of const is limited by the type of the value.
The difference between const and static readonly is that the const value will be replaced on the call site. If you change the value of a const in a future version then all assemblies that rely on your class need to be recompiled using the new value.
The property requires a method call (calling a getter is a method call). So if the value is constant at runtime there is no need for that.
Yes, there is an advantage:
If the value gets changeable at any point in the future (e.g. in a future version of your code), in a way that it is, for example, time-dependent, you can support that in the read-only property without changing the public interface of your class.
If you have to replace a readonly field with a property, you will have to recompile any other assemblies that use your class.
There are two major differences:
The first is that fields cannot be on interfaces, whereas properties can. So if you want to use this in an interface, you have to use the property.
The second, more interesting, is that readonly fields CAN be modified, while the object is being constructed. Take the following code:
public class MyTestClass
{
public readonly int MyInt = 1;
public MyTestClass()
{
MyInt = 2;
}
}
If a caller does
new MyTestClass().MyInt
they will get 2. The same goes for static constructors for a static readonly field.
The way I see it, using the first way describes the intention of the value better - which is that it is immutable. When a person is looking at the class' interface, he will see that the value is read-only, and won't have to wonder whether it can be changed later (since in the second case he can't see the property's implementation).
An important thing to note about const declarations (I don't believe it's true for readonly) is that changing the field's value constitutes an API change, even if you're just changing the value from 42 to 41. The reason is that for consts, the value is determined during compile time, which means that if I compile a module that uses your constant, and you later change it, I will still be using the old value until I recompile my module with your new version.
readonly is nice to use on things that can only be changed in your constructor. Examples of this is typical services as interfaces when you are following the TDD pattern.
In your example const is best, it's a constant after all.
readonly
const
Cheers
I think the first line making something constant or rather readonly using readonly keyword.
and the second line is making use of a property to implement readonly. Both do the same but if you compare with the IL the property would add few extra lines of code to the dll.
The main advantage for me is with readonly you are allowed to declare it anywhere in your code. But, you will get a chance to set it only once. With the setter, you declare and set in one stroke.
Yes, there's a difference between the two.
A readonly field can only be set in the constructor.
A {get; private set;} can be set at anytime from within the class.
Example:
public class Car
{
public readonly string Name;
public string color {get; private set;}
public Car()
{
Name = "Car";
Color = "Red";
}
// will fail compilation
public void ModifyName()
{
Name = "Subaru"
}
// perfectly ok
public void ModifyColor()
{
Color = "Green"
}
}
A Property is just syntactic sugar around a field, a property without a setter is simply declared a readonly field so the compiler will allow you to set it at runtime in the constructor, because to the compiler you are referencing a readonly field. There is a larger discussion around what to use a field or property, which is not within the scope of the question. And yes its this syntactic sugar that you have to do the recompiling referenced by #SOreadytohelp. Just to be clear a property is a field with a get and set method created for it, C# will allow you to reference it like a field rather than doing an annoying call to the getter or setter everytime.
I'm learning C#,and now i'm trying to understand static members and constants.Which is the best way to declare a constant?
This way?
class Myclass
{
public const double G=9.8;
}
Or
class Myclass
{
private static double G{get;set;}
static MyClass()
{
G=9.8;
}
}
I've asked this question because,with the 2 ways i access the membre with the same code:
Console.WriteLine(Myclass.G);
constant:
Constant fields are defined at the time of declaration in the code
snippet, because once they are defined they can't be modified. By
default a constant is static, so you can't define them static from
your side.
It is also mandatory to assign a value to them at the time of
declaration otherwise it will give an error during compilation of the
program snippet. That's why it is also called a compile-time constant.
Explanation:
Consider ff. code:
void Sum(int j)
{
const int i = 9, k = 2;
const int A = i + k;
}
This will produce a result of 11, without showing any error since we already declared it at the initial point of declaration.
But how about:
void Sum(int j)
{
const int i = 9, k = 2;
//const int A = i + k;
Const int B = i + j;
}
This code snippet will take you toward a compile-time error, because there is no initialization, since it's evaluated at run time.
Points to Remember
Compile-time constant
Can't be declared static
Can't be modified or changed
Can be of any type of Access Modifier
Local scope
Needs to get initialized
Declared at the time of declaration
Static
The static keyword is used to declare a static member. If we are
declare a class as a static class then in this case all the class
members must be static too. The static keyword can be used effectively
with classes, fields, operators, events, methods and so on
effectively.
Consider ff. code:
class ReadOnly
{
static int i = 11;
public static void disp()
{
Console.WriteLine(i);
}
}
Explanation:
This code will show no error and produce a result (11), since we declared its value to be static at the time of declaration. So we can access it depending on our use in the program.
But how about this:
class ReadOnly
{
int i = 9;
public static void disp()
{
Console.WriteLine(i);
}
}
This snippet above will show an error, because we didn't declare a value for the static and we are trying to access it within a method. We can't do that.
Points to Remember:
Can't be used with indexers
Works with constructors too
By default it is private
Can be parameterized or public too
If its applied to a class then all the class members need to be static
You can read more about above explanation here: constant vs readonly vs static
Additional note for static methods.
Consider ff. code:
public class SomeClass {
public string SomeMethod() {
return "Hello, World.";
}
}
When you want to Access SomeMethod of SomeClass, you need to instantiate SomeClass first:
var some = new SomeClass();
string result = some.SomeClass(); //this will set result as "Hello, World."
Compared to a static method:
public class SomeClass {
public static string SomeMethod() {
return "Hello, World.";
}
}
When accessing SomeMethod, you don't need to instantiate SomeClass. You can access it directly by:
string result = SomeClass.SomeMethod(); //this will give "Hello, World."
Which is the best way to declare a constant?
Its not the best, its the only way: const double G = 9.8;.
Or (...) static double G { get; set; }
Thats not a constant! Constant means constant: 1 is a constant, 'c'is a constant, PI is a constant... they represent values that don't change, ever!. Your second implementation of G can change, therefore its not a constant.
Also, its important you notice that constants are known at compile time, there is no evaluation needed at runtime.
This is the reason why any reference type const (expect string which has specific compiler support through string literals) can only be initialized to null, any other option would need to be evaluated at runtime.
Its also the reason why only a finite set of value types can be declared as const too. All of them are existing types in the framework and.. surprise, surprise, they all have compiler literal constant support: 1, 'c', 9.8 or 0.25M but not 01/01/2017 (how else would the compiler know the values before runtime?).
Another interesting question you didn't make is: what about static readonly?
You can think of static readonly as "the poor man's" const. Its often used to circumvent the limitations const offers concerning what types and initializing values are allowed.
It is almost the same as a constant, but there are a few important and decisive differences:
It can change; although it is readonly, you can change it's value inside the static constructor of the declaring type. const can never change after initialized.
It is evaluated at runtime, not compile time as a true const.
Any type can be declared as a static readonly and initialized to any valid value as you would do with any regular field.
As a nittpicking side note, you shouldn't make G a constant ;). It changes, and quite a bit. G in Ecuador is different from G in the North Pole.
const variables are assigned values at time of definition.
They are available at compile time. You can even use a compile time evaluate-able expression at compile time. But once a value has been assigned to a const variable, it cannot be changed at any other time.
Using static field means the value will remain same for every user of the application, but this value can be changed by code in any of the classes, and it will change for every user of the application.
Do not use static for constants, use const only. const are by default static, and you cannot use static keyword with it.
Check this
void Main()
{
// You will not be able to change value for const variable.
Console.WriteLine(Myclass.G);
// You will be able to change value for static variable,
// and this change will impact all users of the application.
// For every user, this field will store value of 10 now.
// That will not be required or desired code behavior.
Myclass1.G = 10;
Console.WriteLine(Myclass1.G);
}
// Normal class with const field
class Myclass
{
public const double G=9.8;
}
//static class with static constructor
static class Myclass1
{
public static double G{get;set;}
static Myclass1()
{
G=9.8;
}
}
Read More
Here you are talking about two different things, and this is their definition from MSDN:
1- static modifier: To declare a static member, which belongs to the type itself rather than to a specific object. The static modifier can be used with classes, fields, methods, properties, operators, events, and constructors, but it cannot be used with indexers, finalizers, or types other than classes.
2- const keyword: To declare a constant field or a constant local. Constant fields and locals aren't variables and may not be modified. Constants can be numbers, Boolean values, strings, or a null reference. Don’t create a constant to represent information that you expect to change at any time.
So a static member is defined for a Class (for all its instances, and that's why you can access it directly from the name of the Class) but can be modified. a const field of class can not be modified.
I have a c# program and I have some constant variables that I want to be accessible throughout the program. I won't need to change them at any point.
I have tried a static class and that worked well. I declared a 'static class' and had my variables inside as 'public static'.
The problem came when I wanted to use these unchanging variables in a case statement. Since this only accepts consts, it didn't work out too well.
The question is this: if I have a static class which does not have static variables within it, will this work just as well? This is going from public static to public const.
Thanks for your help.
Yes, consts by default are static.
It depends. Const can't be variables, they must be literals. If you're trying to assign a variable to the const such as a class you made then you have to keep it as static readonly. If you mean to assign a literal such as a number or a string then const is just fine.
A few examples:
public const int Number = 1; // this works; 1 is a literal
public const int Number = SomeClass.SomeProperty; // this does not work
public const int Number = SomeClass.SomeConst; // this works
public const SomeClass Var = new SomeClass(); // does not work
public const string Var = "test"; // this works as "test" is a literal.
If you are not using literals youre better of doing:
public static readonly SomeClass Var = new SomeClass ();
If you are using numeric literals another option is the enum which is basically a static class with some added features.
public enum MyConstants
{
VarOne, // defaults to 0
VarTwo, // defaults to next number (1)
VarThree // defaults to next number (2)
}
Is there any alternative present for Static Field in C# as static field never garbage collected?
If I want to declaure the number of strings, constants which I want to use throughout the program, I am finding a way for that.
You can use a const but it has to be a value.
public class Foo
{
public const string Bar = "Bar";
}
See https://msdn.microsoft.com/en-us/library/e6w8fe1b.aspx
As an addition to Richard Schneiders answer, sometimes you can't use const (the compiler should know the const value at the compiling time), but want to provide constant like behaviour. In that case readonly is the choice:
public class Foo {
// Settings should be read and then preserved intact
public static readonly String Settings = File.ReadAllText(#"C:\MySettings.txt");
...
}
You can Use Const for this.
Const is a reserved word. It allows us to specify that a value is invariant and must not be modified after compile-time. Const values, like const strings, help us simplify and optimize programs.
Eg:
public static class Constants
{
public const string Name = "abc";
}
https://msdn.microsoft.com/en-us/library/acdd6hb7.aspx
Is there any difference between the following?
class C
{
// One:
public static readonly int ValueAsAMember = 42;
// Two:
public static int ValueAsAProperty { get { return 42; } }
}
I'm used to writing constants the first way (unless they're private/internal, in which case I use the const keyword), but I recently saw the second form.
Is there any advantage one way over the other in terms of readability, convention, performance, or anything else?
You have three choices:
public static readonly int Value = 42;
public static int Value { get { return 42; } }
public const int Value = 42;
Choose static readonly if the value will not change at runtime but might change in future versions of your code.
Choose a property if the value might change at runtime. Of course it won't change if you use the given code.
Choose const if the value is really a constant that will not even change in future versions (something like Math.PI or int.MinValue). And of course the use of const is limited by the type of the value.
The difference between const and static readonly is that the const value will be replaced on the call site. If you change the value of a const in a future version then all assemblies that rely on your class need to be recompiled using the new value.
The property requires a method call (calling a getter is a method call). So if the value is constant at runtime there is no need for that.
Yes, there is an advantage:
If the value gets changeable at any point in the future (e.g. in a future version of your code), in a way that it is, for example, time-dependent, you can support that in the read-only property without changing the public interface of your class.
If you have to replace a readonly field with a property, you will have to recompile any other assemblies that use your class.
There are two major differences:
The first is that fields cannot be on interfaces, whereas properties can. So if you want to use this in an interface, you have to use the property.
The second, more interesting, is that readonly fields CAN be modified, while the object is being constructed. Take the following code:
public class MyTestClass
{
public readonly int MyInt = 1;
public MyTestClass()
{
MyInt = 2;
}
}
If a caller does
new MyTestClass().MyInt
they will get 2. The same goes for static constructors for a static readonly field.
The way I see it, using the first way describes the intention of the value better - which is that it is immutable. When a person is looking at the class' interface, he will see that the value is read-only, and won't have to wonder whether it can be changed later (since in the second case he can't see the property's implementation).
An important thing to note about const declarations (I don't believe it's true for readonly) is that changing the field's value constitutes an API change, even if you're just changing the value from 42 to 41. The reason is that for consts, the value is determined during compile time, which means that if I compile a module that uses your constant, and you later change it, I will still be using the old value until I recompile my module with your new version.
readonly is nice to use on things that can only be changed in your constructor. Examples of this is typical services as interfaces when you are following the TDD pattern.
In your example const is best, it's a constant after all.
readonly
const
Cheers
I think the first line making something constant or rather readonly using readonly keyword.
and the second line is making use of a property to implement readonly. Both do the same but if you compare with the IL the property would add few extra lines of code to the dll.
The main advantage for me is with readonly you are allowed to declare it anywhere in your code. But, you will get a chance to set it only once. With the setter, you declare and set in one stroke.
Yes, there's a difference between the two.
A readonly field can only be set in the constructor.
A {get; private set;} can be set at anytime from within the class.
Example:
public class Car
{
public readonly string Name;
public string color {get; private set;}
public Car()
{
Name = "Car";
Color = "Red";
}
// will fail compilation
public void ModifyName()
{
Name = "Subaru"
}
// perfectly ok
public void ModifyColor()
{
Color = "Green"
}
}
A Property is just syntactic sugar around a field, a property without a setter is simply declared a readonly field so the compiler will allow you to set it at runtime in the constructor, because to the compiler you are referencing a readonly field. There is a larger discussion around what to use a field or property, which is not within the scope of the question. And yes its this syntactic sugar that you have to do the recompiling referenced by #SOreadytohelp. Just to be clear a property is a field with a get and set method created for it, C# will allow you to reference it like a field rather than doing an annoying call to the getter or setter everytime.