So, I have an encryption key in my code like:
private const string _keyc = "blahblahblah";
private static string _key
{
get { return "blahblahblah"; }
}
After compilation, on ILDasm, I do notice that I can just see the value of the constant directly, but not in the second case. However, I can still see the key in ldstr under hidebysig...get_key()
ILSpy however obtained back the source code exactly the way I wrote it.
So here, I’m wondering, does it really make sense to use an auto property here? Are there any other advantages in using auto properties? Specifically in this type of simple case, would it be advisable to use an auto property? Thanks!
You can use automatic properties only when:
getandsetaccessors. If you are only defining one accessor, you cannot use automatic properties. (Note that you can define aprivate setaccessor on an automatic property if you want the property to be read-only from code outside of the class, but read-write from inside the class.)reforoutparameter. In particular, this will prevent you from using theSystem.Threading.Interlockedmethods on the field.Based on your example, you are implementing a read-only property (one with no setter). You cannot use automatic properties in this case, unless you use a pattern like this:
However, just returning the constant value from a getter is much less complex, and should be preferred:
This code is clear and to the point. Automatic properties are supposed to make your code more readable. In this case they would actually obfuscate intent, so I would not use one here.
Note that the property in your example code is not an automatic property at all; it’s just a standard property. Automatic properties declare a getter and setter, but do not provide an implementation.