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);
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
//or:
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".
Member
30 Points
328 Posts
Non-String Constant
Jul 02, 2014 12:44 PM|airic82|LINK
Hey, everyone!
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:
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!
-Eric
All-Star
101931 Points
20703 Posts
Re: Non-String Constant
Jul 02, 2014 12:57 PM|MetalAsp.Net|LINK
Use readonly instead.
Refer: http://msdn.microsoft.com/en-us/library/acdd6hb7.aspx
All-Star
114593 Points
18503 Posts
MVP
Re: Non-String Constant
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") :
Member
30 Points
328 Posts
Re: Non-String Constant
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!
Contributor
2132 Points
675 Posts
Re: Non-String Constant
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:
This might not be what you intended. All readonly does is prevent you from later resetting it:
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".
http://www.tangiblesoftwaresolutions.com
Instant C# - VB to C# Converter
Instant VB - C# to VB Converter