I have a property with read/write capability. This particular property points to the log file. What I wanted to know is what is the best modifier to attach to my property "set," so that no one can modify it?
Example:
public static string writeToFile { get; internal set; }
or
public static string writeToFile { get; protected set; }
Is one of these better than the other? Or is there a better way to protect set?
VulpesPosted Dec 12, 2014, 11:03 AM
public static string writeToFile { get; private set; }
The only difference is that the property would have a default value of null rather than an empty string.
In C# 6. 0, you'll be able to do this instead:
public static string writeToFile{ get; } = "";
but we'll have to wait a bit longer to use that :)
MarcPosted Dec 12, 2014, 12:13 PM
VulpesPosted Dec 12, 2014, 12:10 PM
In fact, I think that's how read-only automatic properties will work in C# 6.0. The compiler generated backing field for the property will be marked 'readonly' though this will only be evident if you're accessing it using reflection.
Michal HabalcikPosted Dec 12, 2014, 11:27 AM
MarcPosted Dec 12, 2014, 11:24 AM
MarcPosted Dec 12, 2014, 11:02 AM
Michal HabalcikPosted Dec 12, 2014, 10:52 AM
Did you think about not exposing the setter at all?
Something like:
private static string _whatever = String.Empty;
public static string writeToFile
{
get { return _whatever; }
}