Last post Jul 02, 2014 02:35 PM by David Anton
Jul 02, 2014 12:44 PM|airic82|LINK
This is probably a really basic thing to ask, but how do I make a non-root object a constant so it can never be changed?
Here's my example:
public const NetworkCredential API_CREDENTIALS = new System.Net.NetworkCredential(username, password);
That won't compile because "A const field of a reference type other than string can only be initialized with null."
Well, initializing it to null does me no good because I want it to have a value. I just don't want that value changed.
Is the only way to make a public property that only has a get-statement?
Perhaps I'm overthinking this and my brain is shutting down prior to the long weekend. :)
Thanks in advance for the advice!
Jul 02, 2014 12:57 PM|MetalAsp.Net|LINK
Use readonly instead.
Jul 02, 2014 01:05 PM|Rion Williams|LINK
If you don't want your value to be altered, you could consider using the
readonly keyword instead of a constant (as constants can only be "numbers, Boolean values, strings, or a null reference") :
public readonly NetworkCredential API_CREDENTIALS = new System.Net.NetworkCredential(username, password);
Jul 02, 2014 01:32 PM|airic82|LINK
Thanks, guys. I thought about readonly, but I wasn't sure about that either.
Appreciate the feedback!
Jul 02, 2014 02:35 PM|David Anton|LINK
'readonly' will prevent you from setting it (except for the constructor), but you can always change the state of the object.
e.g., you can always change the username or password anytime:
API_CREDENTIALS.UserName = "something else";
API_CREDENTIALS.Password = "something else";
This might not be what you intended. All readonly does is prevent you from later resetting it:
API_CREDENTIALS = null; //not allowed with 'readonly' after instantiation
API_CREDENTIALS = new System.Net.NetworkCredential(different_username, different_password); //not allowed after initial instantiation
In general, the idea of a "non-changeable" object does not exist in C# - you have some specialized classes that are readonly, but you can't make an arbitrary type instance "unchangeable".