Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
After reading a lot about immutability in C#, and understading it's benefits (no side effects, safe dictionary keys, multithreading...) a question has come to my mind:
Why there is not a keyword in C# for asserting that a class (or struct) is immutable? This keyword should check at compile time that there is no way you can mutate the class (or struct). For example:
public immutable class MyImmutableClass
{
public readonly string field;
public string field2; //This would be a compile time error
public readonly AnyMutableType field3; //This would be a compile time error
public string Prop { get; }
public string Prop2 { get; set; } //This would be a compile time error
public AnyMutableType Prop3 { get; } //This would be a compile time error
}
I think the compiler work would be quite easy, as it would need to check just a few things:
All public fields are readonly.
All public properties only have getters.
All public fields or properties have immutable types as well (simple value types, or immutable classes/structs).
All public functions or public property getters only depend on immutable fields or properties (public fields/props as described before, or private fields/props which comply to the same restrictions). This of course includes Equals(), GetHashCode() and ToString().
Some possible problems come to my mind with this design:
For the compiler to know that a compiled class/struct is immutable, it would probably be necesary to make changes in the intermediate language.
Readonly generic collection (such as IEnumerable<T>) immutability would depend on the immutability of the type <T>. The proposed immutable keyword would not be useful in this context, as you could not declare that IEnumerable<string> is immutable, even though it is.
Are the reasons stated before enough for this keyword to not exist?
Am I missing any other drawbacks?
Is this just not necessary enough for such big changes in the language?
The short version would be: because nobody has proposed, spec'd, designed, implemented, tested, documented, translated and supported that feature.
The longer version would relate to why to do it, given that it can be achieved indirectly with the readonly field - what benefit would it add.
For classes, it turns out to be relatively minor. Note that there is an [ImmutableObject(true)] attribute that can be used, but no features or frameworks really have a use for it, so ... nobody uses it.
There was a proposal to add "readonly structs" in a future version of C# (related to ref locals, Span<T>, etc) - but: it died a death and evaporated. However, the ref readonly stuff lives on, which is intended to prevent reassignment of this in struct instance methods.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
We have a small disagreement within my team over whether injected dependencies should be stored as readonly fields:
public class MyClient
{
private readonly IService service;
public MyClient(IService service)
{
this.service = service;
}
}
or as private readonly properties:
public class MyClient
{
private IService Service { get; }
public MyClient(IService service)
{
Service = service;
}
}
Are there any advantages to one choice over the other? I favour the former but it seems half of our classes use the latter.
You should use a readonly field.
The are three reasons to use properties over fields:
You want to add some extra logic which is run when the property is accessed.
You want to reserve the right to add some extra logic in the future, without changing your interface.
You're using some tool / serialization framework which only deals with properties, and ignores fields.
Point 2 is why people recommend using properties instead of fields for all public (and sometimes protected) members. Point 1 (and perhaps point 3, in rare cases) is the only reason you would create a private property.
None of those points apply here. The property is only adding extra overhead, and there's no reason to pay that cost for zero gain.
I think readonly field is the safest approach as it prevents you from creating a new instance of the field in a different place than the constructor(Single Responsibility Principle). The decision what kind of implementation for interfaces should be used in a given class should be done at the level of the DI container. You can inject different objects for different environments, based on the app settings in your Continuous Delivery pipeline. Though you don't have to worry about weird things like e.g. using some AzureSerive when using OnPremise version of the app etc.
[Using a private readonly property with a getter or a private readonly field is equivalent in term of generated bytecode, so it's just a matter of taste.] <-- this is not true, as pointed below. Sorry for the inconvenience.
I prefer (and use) private fields, as I consider them more clear semantically (in my mind a field is private, fullstop) and less verbose (no need for that awful { get; }, I hate getters 😄).
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
If a class (or a structure) has a field and we replace it with an auto property of the same type, will client code always stay the same, taking into account that we don't use reflection or any other type of direct or indirect meta-programming? For example
int Integer;
public void Test() {
Console.WriteLine(Integer);
}
If I change int Integer to int Integer { get; set; }, the code that uses it stays unchanged. Is there any case when I need to change calling code?
The same question about readonly fields and get-only properties.
EDIT: I clarified my question. Also, taking into account existing answers, instead of auto property, question will be about ref property:
Is it possible to replace this
int Integer;
with
int _integer;
ref int Integer => ref _integer
Without any changes of calling code?
I want to find a case when I need to change client source code if I
replace a field with a property or opposite. I want to know how safe
this replacement is
Fields (C# Programming Guide)
Generally, you should use fields only for variables that have private
or protected accessibility. Data that your class exposes to client
code should be provided through methods, properties and indexers. By
using these constructs for indirect access to internal fields, you can
guard against invalid input values. A private field that stores the
data exposed by a public property is called a backing store or backing
field.
So there you have the official word on field and property usage
I mean, if we replace a field with auto property or opposite, do we
need to change client code in some cases
Yes, you are likely to break things in the following cases,
If you are exposing fields that are being passed by ref
If this class is being inherited and in cases where fields or properties are getting re-implemented or overridden
A derived classes implement Interfaces that require properties etc.
Also there could be cases where they are used in Expressions and it expects field or a property (I think).
In short, if large code bases relied on fields/properties and you change them this is likely to cause breakable changes for any of the above.
Though in summary, if you lived by the Microsoft recommendations above, you should have less of a problem, and if you do it points to the fact this should probably be refactored as a new version anyway (with breakable changes, and more expected usage).
This question already has answers here:
Is there an easy way to make an immutable version of a class?
(7 answers)
How do I create an immutable Class?
(8 answers)
Closed 5 years ago.
I want to see if I can make an instance of a class immutable even if the class itself isn't. What I have here is a similar situation to IntPtr.Zero and other static fields like that, except it's a mutable class and not a struct.
class TestClass
{
public static readonly TestClass GoldStandard = new TestClass();
public int field = 0;
}
class Program
{
static void Main(string[] args)
{
TestClass test = TestClass.GoldStandard;
test.field = 1; // I want to keep this from happening.
Console.WriteLine(TestClass.GoldStandard.field);
}
}
What can I do to keep GoldStandard from being modified?
EDIT: I regret that my question was so badly misunderstood. This is clearly not a duplicate of Immutable type and property in C# or How do I create an immutable Class?. Those questions are about how to create an immutable class, and not how to create an immutable instance of a mutable class.
As for Is there an easy way to make an immutable version of a class?, it certainly sounds very similar to my question. However, there are some important reasons it shouldn't count.
The question asks how to make an instance immutable at some point during the instance's lifetime, rather than just having one instance of a mutable class be immutable from the start.
The question asks how an immutable second class can be generated to mimic a mutable class, rather than having one mutable class act as immutable in a specific case.
The answer to the question doesn't even address my question at all, and is mostly about how immutable classes work in general.
I understand moderators can't take too much time to understand the questions in depth when they're scanning for duplicates, but I hardly think it's fair for my question to be closed as a duplicate because of such superficial similarities.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
It seemed like this was possible, but I can't find a reference on how to accomplish it, though I've seen a few things that are closely related. I have a particular type of class that requires a public or private default ctor. The reason is stylistic; it is a domain aggregate and the only case where a default ctor should be used is during event store replay. There are obvious ways to work around this, but I'm trying to lock this particular type down. At any rate, what I'm hoping to do is create an attribute that can be applied at the class level that would enforce the existence of a default ctor. If one isn't found, it won't compile... or at the very least, give it the big nasty blue underline like [Obsolete()] does. I figured this was potentially doable with Roslyn. Any direction would help. The solution would ideally travel with the project rather than being something that needs to be installed on visual studio.
Just a simple idea, for a public default constructor you could make use of the where T : new() constraint - even though attributes cannot be generic you can supply typeof(HasDefaultConstructor<MyClass>) as an argument to an attribute:
public static class HasDefaultConstructor<T> where T : new() { }
public class CheckAttribute : Attribute
{
public CheckAttribute(Type type) { }
}
[Check(typeof(HasDefaultConstructor<MyClass>))]
public class MyClass
{
public MyClass() { }
}
But it feels a bit hacky having to supply the type you're applying the attribute to, and doesn't work for the non-public constructors, but it does fail at compile-time without needing any addons.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Is there a standard or accepted code style for whether public or private members / functions come first in a class?
I expected to find a lot on Google regarding this but have found nothing.
Take a look at this SO question. It has the StyleCop Rules Documentation's requirements.
Fairly well used standard.
ASIDE: There is a free plugin for C#. Makes following the rules much simpler when you know what you are doing wrong. It will tell you if you violate the rules and can be set to run during the build step.
There are ordering rules with StyleCop which are useful to follow as a point of standardisation.
No this is simply a matter of personal preferences. Just follow your company one if that applies.
As people are saying, the order generally doesn't matter. However, there is one important exception, and that's initializing static fields. You can initialize static fields based on the value of other static fields - it all ends up getting compiled into the static constructor, but in the order that it's written in the code.
For example:
class Program {
private static int j = 4;
private static int i = Program.j;
static void Main(string[] args) {
Console.WriteLine(Program.i); // 4
}
}
But:
class Program {
private static int i = Program.j;
private static int j = 4;
static void Main(string[] args) {
Console.WriteLine(Program.i); // 0
}
}
So keep this case in mind if you decide to re-shuffle your members around. To be totally safe, you can put the initializations in the static constructor, like:
class Program {
private static int i;
private static int j;
static Program() {
Program.j = 4;
Program.i = Program.j;
}
}
There are rules enforced by StyleCop that I have seen many people use as a standard.
Frankly, they make sense1, but I don't think it's the best way.
I think things should be grouped by functionality, not by type, or accessibility, or static, etc. I would argue that a scheme that is organized by functionality requires the least amount of navigation when trying to read or maintain a code base. Any other ordering scheme (or *rules) would leave you navigating all over the class as you try to work with it. A conceptual ordering that places things together that make sense will minimize that jumping around. It's about making it easier to understand and work with it. It's a practical perspective, rather than forming rules for the sake of having rules that can be enforced.
1: They make sense in that they are a rule, they appeal to the OCD among us, and they can be enforced by a machine, but who cares if the machine can enforce them? But code is not for the machine, it is for the humans. When I need to understand the code, I don't think to myself "if only I could first understand all the constant fields, and then all the fields, etc." I take a very different approach. I want to see the big picture first, and one thing that is going to assist with that is seeing the code organized by functionality.
Here is the Microsoft C# Coding Conventions (C# Programming Guide)
It makes no mention of ordering for public, protected or private functions or members in a class.
I know in my past experience that FxCop had "suggested" that I put my public functions before my private functions, but again not necessarily a standard.