I have a class Constants in which I store a number of static readonly variables.
Should I do this:
private static readonly int _maxThings = 100;
...
public static int MaxThings { get { return _maxThings; } }
That seems kind of redundant to me. Is there any reason why I wouldn't just do the following?
public static int MaxThings { get { return 100; } }
Edit
Okay, so this was a brain fart of a question. I think the point is that if I'm going to be setting this value at initialization then it makes sense to use a static backing field and expose a public get-only property that wouldn't need to be static itself.
If, however, I'm comfortable setting a public static property to a hard value, then there's no functional difference between that and just baking it into the assembly. Unless there's some other concept I'm missing here, in this case I'd just use a const.
Thanks for the answers.
you should do
public const int MaxThings = 100;
there is no reason that i can see to use properties in this case.
Update ->
In response to comments.. If you are developing a library and exporting constants then it's important to understand how constants are consumed int .net. When compiled against your library, the constant values will be inlined and included in the consuming application, such that if your library is updated and consuming application is not then the old constant values will still be present. This is, of course, when static properties should be used.
If you are not developing a library, then the use of const's are fine.
Because constants are well... constant, the value will never change.
The preference for properties are that the signature of a field and a property are different. So changing from a field to a property requires that all callers are recompiled. Thus creating a property in the first instance will avoid that issue if you need to add getter/setter logic at a later date.
Because you have a constant, which will never change, there is no reason at all to implement it as a property. Although you defined a readonly static, as this can only be changed from within the class, externally there is no difference between that and a constant.
From a code readability standpoint I find the second one to be an improvement. Not sure if the compiler is smart enough to optimize in that situation, but the hit is so negligible I would just go with readability.
Related
A couple of days ago I asked myself about the difference, if any, between initializing static fields via
the static constructor and doing so by using a static field initializer (inline initialization of a static field at the point of declaration).
After reading plenty of stackoverflow questions on the subject and the famous Jon Skeet's article on the beforefieldinit flag I've now a much better understanding of the difference between the two initialization strategies.
There is one point that I'm not sure about, mostly because I wasn't able to find any official documentation about it.
The static construcutor is guaranteed to be executed only once and I think this holds true even in multi threading scenarios (when different threads create instances of the class and / or use static members of the class. In any case, the static constructor runs once and only once).
Is this true even for the inline initialization of the static fields ? Is the inline initialization of a static field guaranteed to be executed once even in multi threaded scenarios ?
Another point I'm still missing is what are the practical consequences of this difference in the initialization of the static fields of a class. Put another way, I would like to understand when the correctness of a piece of code can be affected by the choice of initializing a static fied inline at the point of declaration (instead of using the static constructor).
Most of the time (this depends mostly on the type of code that I usually work on, namely web applications) I use static readonly fields in service classes to store things that are used by the service I'm writing to perform computations or taking decisions. I decide to put these things inside static fields because they need to be the same for all the possible instances of the class I'm writing, they are actually invariants that don't belong to a particular instance, but instead they belong to the algorithm itself.
This is an example:
public class SomeInterestingService
{
private static readonly int ConstantNumber = 13;
private static readonly string[] Names = new[] { "bob", "alice" };
private readonly INumberGenerator numberGenerator;
public SomeInterestingService(INumberGenerator numberGenerator)
{
this.numberGenerator = numberGenerator ?? throw new ArgumenNullException(nameof(numberGenerator));
}
public int ComputeMagicNumber()
{
int answer = this.numberGenerator.GetNumber();
foreach(var name in names)
{
answer += name.Length;
}
answer += ConstantNumber;
return answer;
}
}
In code like this, is there any practical difference in chosing static constructor initialization or inline initialization of the static fields ConstantNumber and Names, apart from the difference in performance (inline initialization is more performant due to runtime optimizations that are not possible when using the static constructor) ?
Can the correctness of the code above be affected by the coiche in any strange corner case ? (I think not)
Original question:
In code like this, is there any practical difference in chosing static
constructor initialization or inline initialization of the static
fields ConstantNumber and Names, apart from the difference in
performance (inline initialization is more performant due to runtime
optimizations that are not possible when using the static constructor)
?
The answer is no. Either those properties are set upon each construction of the class (instance properties) or set upon the first call to any of the members or methods to the class (static properties).
What #Henk Holterman is saying that because the array of names is a reference type you could theoretically change any of the values in the array. Like:
Names[0] = "Henk Holterman";
Even though the property is readonly. Meaning, you can't assign a new instance of array to that property. The values in the array are not readonly. And could be manipulated if public or by calling a method of that class.
In a discussion with a peer, it was brought up that we should consider using auto properties for all class level variables... including private ones.
So in addition to a public property like so:
public int MyProperty1 { get; set; }
Our private class-level variables would look like this:
private int MyProperty2 { get; set; }
Instead of:
private int _myProperty2;
I'm on the fence about why someone would want to do this but I can't decide if my reluctance to accept this is because of my own internal brainwashing with how I write my code to the same programming standards and naming conventions I've used for 10 years or because I've never seen this before (for a reason).
I realize it's extra code to type but to be honest, when using auto-properties, I don't think I've ever typed it out due to the 'prop' and 'propg' snippets so it'd be very simple to set up a new snippet to create a private auto property so the extra code doesn't bother me too much since I never have to type it.
Other than aesthetics which may just be my subconscious, are there any issues that could result from using fully private auto properties? Are there any good reasons to do this or not to do it? I've seen a lot of code in my day on stackoverflow, codeplex, codeproject, etc. and I've never seen anyone use this standard.... is there a reason why?
Private auto-properties are completely pointless, in my opinion. What value does a private auto-property provide that a plain field doesn't?
(It's different when the auto-property is only partially private -- eg, a public/protected getter with a private setter -- or when you use a private non-automatic property to enable you to wrap additional code around the getter/setter.)
This does not make too much sense.
I can think of a 'benefit':
you can later add logic to the getter and/or setter and be sure it is always passed
but frankly your classes should not become so big that this is useful.
"are there any issues" ?
Your properties won't work as arguments to ref or out parameters.
It's not nearly as useful for privates as for publics.
Suppose you took your automatic private property and later built some logic into it (being able to do that without breaking anything is the whole point of auto props)...
This would require you to create a private backing member for the property to wrap.
So now you've got two different private ways (member and property) of doing the same thing though one has hidden side effects (the property) and you've now also got the problem of ensuring none of your other methods in the class access that member directly.
Ends up being much more of a headache than just using a private member from the beginning.
What this strategy will do for you is provide an opportunity to put any future changes into the previously autogenerated private property without affecting any of the other code that gets or sets your private property. I personally haven't used this much but it can be beneficial in a case where changes to handling may occur. It also standardizes the code so that fields are always accessed by properties. There are no real drawbacks but it is not really much benefit in most situations either. I think style is really the biggest driver in most situations.
In a discussion with a peer, it was
brought up that we should consider
using auto properties for all class
level variables... including private
ones.
This will not be useful, In case you don't have any logic to write in your properties for retrieving and returning values.
Besides point 1, you have read only property
So you can directly go with
public int MyProperty1 { get; set; }
Moreover it reduces your line of code and Quick Implementation
I'm a firm believer in KISS. I never use a property when a field will do, and I see very little reason to use private accessors (get).
The primary purpose of a property is to be a public accessor for private data. So for simple propreties that do nothing but set or get a value, private accessors and setters make no sense.
Having said that, when you need to transform the data as it's being read, or when you need to perform a side effect when updating the value, you should use a field. Does changing your value raise an event? Then a field is a no-brainer. But then, that's not an auto field that you're declaring with {get; set;}
I was wondering what's considered the C# best practice, private/protected members with public getters, or public getters with private/protected setters?
public int PublicGetPrivateSetter
{
get;
private set;
}
private int _privateMember;
public int PublicGetPrivateMember
{
get { return _privateMember; }
}
I feel that using a private member is more explicit in your code that it's a private setter (using naming conventions).
On the other hand using private setters gives you an option to use virtual (protected), write less code, has less room for mistakes and can give you an option to add a side effect later on if you need to.
I couldn't find what's considered a best practice, or even if one is considered better than the other. From what I've seen usually 80% of the time (from code that I'VE seen) people DONT use private setters... I'm not sure if this is because people don't know about private setters, or because it's considered better to actually use private members.
EDIT:
Indeed, other benefits which I forgot about when using private members is default values and the use of readonly.
I prefer to use auto-implemented properties unless the default implementation doesn't do what I want. So in this case, since the auto-implemented property does what you need, just use that:
public int Foo { get; private set; }
However another situation is if you want to make the field readonly (meaning that the only place where the field can be set is in the constructor). Then you need to define the backing field and mark it readonly as this isn't supported by auto-implemented properties:
private readonly int foo;
public int Foo
{
get { return foo; }
}
There is no best practice I'm aware of. I know automatic properties were mainly to make things easier even more easier for code generation and LINQ related stuff.
For me, I start with automatic properties and refactor later if needed. Depending on the need I may change something to virtual or protected as you mentioned, or maybe refactor to use a variable (When I want to refactor the set accessor to have some logic.
Its the same thing. In the first example, the compiler generates the backing store. In the second, you generated the backing store. Since the implementation is internal to the class, refactoring one into the other is not a big deal. Tools like Resharper make that trivial. The reason you probably haven't seen private setters that much is that its a C# 3.0 feature.
There's nothing wrong with private setters. In most case, it's used with auto properties to make the property readonly outside the object's scope.
Conceptualy speaking, it doesn't change anything. It's mostly a matter of taste.
I personnally use the private setter because I'm lazy and use the propg snippet a lot. (propg tab tab)
Also, most of the time I end up setting dirty flags and binding events to those properties, so I might as well do a part of the work right now. If you ever need to add a setter later, it's much easier if the code is written without using the member behind since the beggining as it will be less code to change.
There is no good answer to this question. the best pratice is to follow our compagnie nomenclature and if your alone then the way you prefer
In my opinion there is no best practice and very little (if any) difference in the resulting compiled code, it really just depends on your needs or own likes/dislikes. If you're following your group's naming standards and meeting requirements (e.g. don't need to propagate a change notification) then it shouldn't matter.
An advantage of private fields is that you can define a default value in the same place as your declaration. In an auto-implemented property you'll have do define the default in the constructor if it's not null or the type's default value.
However, I still like private setters. But we usually don't use auto-implemented properties since our setters usually have a richer functionality - e.g. property update notifications, logging, etc.
I just realized that the C# property construct can also be used with a private access modifier:
private string Password { get; set; }
Although this is technically interesting, I can't imagine when I would use it since a private field involves even less ceremony:
private string _password;
and I can't imagine when I would ever need to be able to internally get but not set or set but not get a private field:
private string Password { get; }
or
private string Password { set; }
but perhaps there is a use case with nested / inherited classes or perhaps where a get/set might contain logic instead of just giving back the value of the property, although I would tend to keep properties strictly simple and let explicit methods do any logic, e.g. GetEncodedPassword().
Does anyone use private properties in C# for any reason or is it just one of those technically-possible-yet-rarely-used-in-actual-code constructs?
Addendum
Nice answers, reading through them I culled these uses for private properties:
when private fields need to be lazily loaded
when private fields need extra logic or are calculated values
since private fields can be difficult to debug
in order to "present a contract to yourself"
to internally convert/simplify an exposed property as part of serialization
wrapping global variables to be used inside your class
I use them if I need to cache a value and want to lazy load it.
private string _password;
private string Password
{
get
{
if (_password == null)
{
_password = CallExpensiveOperation();
}
return _password;
}
}
The primary usage of this in my code is lazy initialization, as others have mentioned.
Another reason for private properties over fields is that private properties are much, much easier to debug than private fields. I frequently want to know things like "this field is getting set unexpectedly; who is the first caller that sets this field?" and it is way easier if you can just put a breakpoint on the setter and hit go. You can put logging in there. You can put performance metrics in there. You can put in consistency checks that run in the debug build.
Basically, it comes down to : code is far more powerful than data. Any technique that lets me write the code I need is a good one. Fields don't let you write code in them, properties do.
perhaps there is a use case with nested / inherited classes or perhaps where a get/set might contain logic instead of just giving back the value of the property
I personally use this even when I don't need logic on the getter or setter of a property. Using a property, even a private one, does help future-proof your code so that you can add the logic to a getter later, if required.
If I feel that a property may eventually require extra logic, I will sometimes wrap it into a private property instead of using a field, just so I don't have to change my code later.
In a semi-related case (though different than your question), I very frequently use the private setters on public properties:
public string Password
{
get;
private set;
}
This gives you a public getter, but keeps the setter private.
One good usage for private get only properties are calculated values. Several times I've had properties which are private readonly and just do a calculation over other fields in my type. It's not worthy of a method and not interesting to other classes so private property it is.
Lazy initialization is one place where they can be neat, e.g.
private Lazy<MyType> mytype = new Lazy<MyType>(/* expensive factory function */);
private MyType MyType { get { return this.mytype.Value; } }
// In C#6, you replace the last line with: private MyType MyType => myType.Value;
Then you can write: this.MyType everywhere rather than this.mytype.Value and encapsulate the fact that it is lazily instantiated in a single place.
One thing that's a shame is that C# doesn't support scoping the backing field to the property (i.e. declaring it inside the property definition) to hide it completely and ensure that it can only ever be accessed via the property.
The only one usage that I can think of
private bool IsPasswordSet
{
get
{
return !String.IsNullOrEmpty(_password);
}
}
Properties and fields are not one to one. A property is about the interface of a class (whether talking about its public or internal interface), while a field is about the class's implementation. Properties should not be seen as a way to just expose fields, they should be seen as a way to expose the intent and purpose of the class.
Just like you use properties to present a contract to your consumers on what constitutes your class, you can also present a contract to yourself for very similar reasons. So yes, I do use private properties when it makes sense. Sometimes a private property can hide away implementation details like lazy loading, the fact that a property is really a conglomeration of several fields and aspects, or that a property needs to be virtually instantiated with each call (think DateTime.Now). There are definitely times when it makes sense to enforce this even on yourself in the backend of the class.
I use them in serialization, with things like DataContractSerializer or protobuf-net which support this usage (XmlSerializer doesn't). It is useful if you need to simplify an object as part of serialization:
public SomeComplexType SomeProp { get;set;}
[DataMember(Order=1)]
private int SomePropProxy {
get { return SomeProp.ToInt32(); }
set { SomeProp = SomeComplexType.FromInt32(value); }
}
I use private properties to reduce code for accessing sub properties which often to use.
private double MonitorResolution
{
get { return this.Computer.Accesories.Monitor.Settings.Resolution; }
}
It is useful if there are many sub properties.
One thing I do all the time is store "global" variables/cache into HttpContext.Current
private static string SomeValue{
get{
if(HttpContext.Current.Items["MyClass:SomeValue"]==null){
HttpContext.Current.Items["MyClass:SomeValue"]="";
}
return HttpContext.Current.Items["MyClass:SomeValue"];
}
set{
HttpContext.Current.Items["MyClass:SomeValue"]=value;
}
}
I use them every now and then. They can make it easier to debug things when you can easily put in a breakpoint in the property or you can add a logging statement etc.
Can be also be useful if you later need to change the type of your data in some way or if you need to use reflection.
I know this question is very old but the information below was not in any of the current answers.
I can't imagine when I would ever need to be able to internally get but not set
If you are injecting your dependencies you may well want to have a Getter on a Property and not a setter as this would denote a readonly Property. In other words the Property can only be set in the constructor and cannot be changed by any other code within the class.
Also Visual Studio Professional will give information about a Property and not a field making it easier to see what your field is being used.
It is a common practice to only modify members with get/set methods, even private ones. Now, the logic behind this is so you know your get/set always behave in a particular way (for instance, firing off events) which doesn't seem to make sense since those won't be included in the property scheme... but old habits die hard.
It makes perfect sense when there is logic associated with the property set or get (think lazy initialization) and the property is used in a few places in the class.
If it's just a straight backing field? Nothing comes to mind as a good reason.
Well, as no one mentioned you can use it to validate data or to lock variables.
Validation
string _password;
string Password
{
get { return _password; }
set
{
// Validation logic.
if (value.Length < 8)
{
throw new Exception("Password too short!");
}
_password = value;
}
}
Locking
object _lock = new object();
object _lockedReference;
object LockedReference
{
get
{
lock (_lock)
{
return _lockedReference;
}
}
set
{
lock (_lock)
{
_lockedReference = value;
}
}
}
Note: When locking a reference you do not lock access to members of the referenced object.
Lazy reference: When lazy loading you may end up needing to do it async for which nowadays there is AsyncLazy. If you are on older versions than of the Visual Studio SDK 2015 or not using it you can also use AsyncEx's AsyncLazy.
One more usage would be to do some extra operations when setting value.
It happens in WPF in my case, when I display some info based on private object (which doesn't implement INotifyPropertyChanged):
private MyAggregateClass _mac;
private MyAggregateClass Mac
{
get => _mac;
set
{
if(value == _mac) return;
_mac = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(DisplayInfo)));
}
}
public string DisplayInfo => _mac.SomeStringInformationToDisplayOnUI;
One could also have some private method, such as
private void SetMac(MyAggregateClass newValue)
to do that.
Some more exotic uses of explicit fields include:
you need to use ref or out with the value - perhaps because it is an Interlocked counter
it is intended to represent fundamental layout for example on a struct with explicit layout (perhaps to map to a C++ dump, or unsafe code)
historically the type has been used with BinaryFormatter with automatic field handling (changing to auto-props changes the names and thus breaks the serializer)
Various answers have mentioned using properties to implement a lazy member. And this answer discussed using properties to make live aliases. I just wanted to point out that those two concepts sometimes go together.
When using a property to make an alias of another object's public property, the laziness of that property is preserved:
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private IDbConnection Conn => foo.bar.LazyDbConnection;
On the other hand, retrieving that property in the constructor would negate the lazy aspect:
Conn = foo.bar.LazyDbConnection;
Looking into the guideline (Properties (C# Programming Guide)) it seems no one expects to use properties as private members.
Properties enable a class to expose a public way of getting and setting values, while hiding implementation or verification code.
In any case it can be interchanged by one or two methods and vice versa.
So the reason can be to spare parentheses on getting and get field syntax on setting.
What are the benefits of having a member variable declared as read only? Is it just protecting against someone changing its value during the lifecycle of the class or does using this keyword result in any speed or efficiency improvements?
I don't believe there are any performance gains from using a readonly field. It's simply a check to ensure that once the object is fully constructed, that field cannot be pointed to a new value.
However "readonly" is very different from other types of read-only semantics because it's enforced at runtime by the CLR. The readonly keyword compiles down to .initonly which is verifiable by the CLR.
The real advantage of this keyword is to generate immutable data structures. Immutable data structures by definition cannot be changed once constructed. This makes it very easy to reason about the behavior of a structure at runtime. For instance, there is no danger of passing an immutable structure to another random portion of code. They can't changed it ever so you can program reliably against that structure.
Robert Pickering has written a good blog post about the benefits of immutability. The post can be found here or at the archive.org backup.
The readonly keyword is used to declare a member variable a constant, but allows the value to be calculated at runtime. This differs from a constant declared with the const modifier, which must have its value set at compile time. Using readonly you can set the value of the field either in the declaration, or in the constructor of the object that the field is a member of.
Also use it if you don't want to have to recompile external DLLs that reference the constant (since it gets replaced at compile time).
There are no apparent performance benefits to using readonly, at least none that I've ever seen mentioned anywhere. It's just for doing exactly as you suggest, for preventing modification once it has been initialised.
So it's beneficial in that it helps you write more robust, more readable code. The real benefit of things like this come when you're working in a team or for maintenance. Declaring something as readonly is akin to putting a contract for that variable's usage in the code. Think of it as adding documentation in the same way as other keywords like internal or private, you're saying "this variable should not be modified after initialisation", and moreover you're enforcing it.
So if you create a class and mark some member variables readonly by design, then you prevent yourself or another team member making a mistake later on when they're expanding upon or modifying your class. In my opinion, that's a benefit worth having (at the small expense of extra language complexity as doofledorfer mentions in the comments).
To put it in very practical terms:
If you use a const in dll A and dll B references that const, the value of that const will be compiled into dll B. If you redeploy dll A with a new value for that const, dll B will still be using the original value.
If you use a readonly in dll A and dll B references that readonly, that readonly will always be looked up at runtime. This means if you redeploy dll A with a new value for that readonly, dll B will use that new value.
There is a potential case where the compiler can make a performance optimization based on the presence of the readonly keyword.
This only applies if the read-only field is also marked as static. In that case, the JIT compiler can assume that this static field will never change. The JIT compiler can take this into account when compiling the methods of the class.
A typical example: your class could have a static read-only IsDebugLoggingEnabled field that is initialized in the constructor (e.g. based on a configuration file). Once the actual methods are JIT-compiled, the compiler may omit whole parts of the code when debug logging is not enabled.
I have not checked if this optimization is actually implemented in the current version of the JIT compiler, so this is just speculation.
Keep in mind that readonly only applies to the value itself, so if you're using a reference type readonly only protects the reference from being change. The state of the instance is not protected by readonly.
Surprisingly, readonly can actually result in slower code, as Jon Skeet found when testing his Noda Time library. In this case, a test that ran in 20 seconds took only 4 seconds after removing readonly.
https://codeblog.jonskeet.uk/2014/07/16/micro-optimization-the-surprising-inefficiency-of-readonly-fields/
Don't forget there is a workaround to get the readonly fields set outside of any constructors using out params.
A little messy but:
private readonly int _someNumber;
private readonly string _someText;
public MyClass(int someNumber) : this(data, null)
{ }
public MyClass(int someNumber, string someText)
{
Initialise(out _someNumber, someNumber, out _someText, someText);
}
private void Initialise(out int _someNumber, int someNumber, out string _someText, string someText)
{
//some logic
}
Further discussion here: http://www.adamjamesnaylor.com/2013/01/23/Setting-Readonly-Fields-From-Chained-Constructors.aspx
Adding a basic aspect to answer this question:
Properties can be expressed as readonly by leaving out the set operator. So in most cases you will not need to add the readonly keyword to properties:
public int Foo { get; } // a readonly property
In contrast to that: Fields need the readonly keyword to achieve a similar effect:
public readonly int Foo; // a readonly field
So, one benefit of marking a field as readonly can be to achieve a similar write protection level as a property without set operator - without having to change the field to a property, if for any reason, that is desired.
Be careful with private readonly arrays. If these are exposed a client as an object (you might do this for COM interop as I did) the client can manipulate array values. Use the Clone() method when returning an array as an object.
Another interesting part of usage of readonly marking can be protecting field from initialization in singleton.
for example in code from csharpindepth:
public sealed class Singleton
{
private static readonly Lazy<Singleton> lazy =
new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance { get { return lazy.Value; } }
private Singleton()
{
}
}
readonly plays small role of protecting field Singleton from being initialized twice. Another detail is that for mentioned scenario you can't use const because const forces creation during compile time, but singleton makes creation at run time.
If you have a pre defined or pre calculated value that needs to remain same through out the program then you should use constant but if you have a value that needs to be provided at the runtime but once assigned should remain same throughout the program u should use readonly. for example if you have to assign the program start time or you have to store a user provided value at the object initialization and you have to restrict it from further changes you should use readonly.
readonly can be initialized at declaration or get its value from the constructor only. Unlike const it has to be initialized and declare at the same time.
readonly has everything const has, plus constructor initialization
code https://repl.it/HvRU/1
using System;
class MainClass {
public static void Main (string[] args) {
Console.WriteLine(new Test().c);
Console.WriteLine(new Test("Constructor").c);
Console.WriteLine(new Test().ChangeC()); //Error A readonly field
// `MainClass.Test.c' cannot be assigned to (except in a constructor or a
// variable initializer)
}
public class Test {
public readonly string c = "Hello World";
public Test() {
}
public Test(string val) {
c = val;
}
public string ChangeC() {
c = "Method";
return c ;
}
}
}
There can be a performance benefit in WPF, as it removes the need for expensive DependencyProperties. This can be especially useful with collections