What is the main difference between the following two declarations?
public string Name
{
get { return "Settings"; }
}
and
public const string Name = "Settings";
Aren’t both prevented from being changed?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The first is a property which only provides a get accessor. This is specified per instance.
The second is a compile time constant. At compile time, it will be replaced with
"Settings", so it is not really a member of the type at all.The
constdeclaration does have the advantage of eliminating a method call (as it’s just a compile time constant value), however, the property call will likely get eliminated by the JIT at runtime.The property declaration has the advantage of allowing you to change how this works later, without breaking compatibility – even binary compatibility. In order to see a change in the const value, a full recompilation of everything that uses it would be required, even if it’s in separate assemblies.
Basically, a
public constis probably a good idea, but only if this is a value that will never change – not a value that will never change during the runtime of the program, but that will never change anywhere, at any time.Int32.MaxValueis a good example – this has a specific meaning that is based on theInt32type itself – there’s no way that this would ever change. As such, it makes sense as apublic const. In your case,"Settings"may be something you’d want to change eventually – if that’s the case, then encapsulating it in a property makes sense.