Reputation: 5768
I have a field which is static and readonly. The requirement is that the value should be allocated to the field at the login time and after that it should be readonly. How can i achieve this ?
public static class Constant
{
public static readonly string name;
}
Kindly guide.
Upvotes: 2
Views: 3033
Reputation: 4907
public static class Constant
{
public static string Name
{
get
{
return name;
}
set
{
if (name == null)
name = value;
else
throw new Exception("...");
}
}
private static string name;
}
Upvotes: 1
Reputation: 4655
You can also create a static constructor in your static class
static Constant()
{
name = "Name";
}
Upvotes: 0
Reputation: 3362
If you declare a readonly field you can only set it in the constructor of the class. What you could do is implementing a property only having a getter and exposing a change method that is used during your logon sequence to modify the value. Other Parts of your program can use the property effectivly not allowing them to change the value.
Upvotes: 3
Reputation: 7452
you need a static constructor
public static class Constant
{
public static readonly string name;
static Constant()
{
name = "abc";
}
}
Upvotes: 1
Reputation: 12458
Just assign the value in the declaration (or constructor) like this:
public static class Constant
{
public static readonly string name = "MyName";
}
readonly
is sugar for the compiler, telling him, that you don't intend to change the value outside the constructor. If you do so, he will generate an error.
Upvotes: 0