I have a static class that has only static properties and a static constructor. When I try to access or set the value of property (with a backing field) the static constructor is not called. However, if I define a static method and try to call it the constructor is executed.
I believe properties are just syntactical sugar and are internally translated as methods. So why does the runtime treats them differently? My class define is given below:
Edit: I have removed the code where I was initializing the value of _fileEncodingText inline.
Edit: The constructor is called but the property is not set. This is probably because "a static constructor runs exactly zero or one times, and runs before a static method call or instance creation in its type". Igor Ostrovsky and Eric Lippert have explained it in their blogs
- http://blogs.msdn.com/b/pfxteam/archive/2011/05/03/10159682.aspx
http://ericlippert.com/2013/01/31/the-no-lock-deadlock/
internal static class AppSettings { static AppSettings() { FileEncodingText = "UTF8"; }
private static string _fileEncodingText; public static string FileEncodingText { get { return _fileEncodingText; } set { string oldValue = _fileEncodingText; _fileEncodingText = value; try { FileEncoding = Encoding.GetEncoding(value); } catch (System.Exception) { _fileEncodingText = oldValue; FileEncoding = Encoding.UTF8; } } } public static Encoding FileEncoding { get; private set; }}
"UTF8"to the class variable anyway. You would normally use a static constructor in a non-static class.