Difference between having no setter and readonly? Is there a difference? [duplicate] - c#

Is there any difference between the following?
class C
{
// One:
public static readonly int ValueAsAMember = 42;
// Two:
public static int ValueAsAProperty { get { return 42; } }
}
I'm used to writing constants the first way (unless they're private/internal, in which case I use the const keyword), but I recently saw the second form.
Is there any advantage one way over the other in terms of readability, convention, performance, or anything else?

You have three choices:
public static readonly int Value = 42;
public static int Value { get { return 42; } }
public const int Value = 42;
Choose static readonly if the value will not change at runtime but might change in future versions of your code.
Choose a property if the value might change at runtime. Of course it won't change if you use the given code.
Choose const if the value is really a constant that will not even change in future versions (something like Math.PI or int.MinValue). And of course the use of const is limited by the type of the value.
The difference between const and static readonly is that the const value will be replaced on the call site. If you change the value of a const in a future version then all assemblies that rely on your class need to be recompiled using the new value.
The property requires a method call (calling a getter is a method call). So if the value is constant at runtime there is no need for that.

Yes, there is an advantage:
If the value gets changeable at any point in the future (e.g. in a future version of your code), in a way that it is, for example, time-dependent, you can support that in the read-only property without changing the public interface of your class.
If you have to replace a readonly field with a property, you will have to recompile any other assemblies that use your class.

There are two major differences:
The first is that fields cannot be on interfaces, whereas properties can. So if you want to use this in an interface, you have to use the property.
The second, more interesting, is that readonly fields CAN be modified, while the object is being constructed. Take the following code:
public class MyTestClass
{
public readonly int MyInt = 1;
public MyTestClass()
{
MyInt = 2;
}
}
If a caller does
new MyTestClass().MyInt
they will get 2. The same goes for static constructors for a static readonly field.

The way I see it, using the first way describes the intention of the value better - which is that it is immutable. When a person is looking at the class' interface, he will see that the value is read-only, and won't have to wonder whether it can be changed later (since in the second case he can't see the property's implementation).
An important thing to note about const declarations (I don't believe it's true for readonly) is that changing the field's value constitutes an API change, even if you're just changing the value from 42 to 41. The reason is that for consts, the value is determined during compile time, which means that if I compile a module that uses your constant, and you later change it, I will still be using the old value until I recompile my module with your new version.

readonly is nice to use on things that can only be changed in your constructor. Examples of this is typical services as interfaces when you are following the TDD pattern.
In your example const is best, it's a constant after all.
readonly
const
Cheers

I think the first line making something constant or rather readonly using readonly keyword.
and the second line is making use of a property to implement readonly. Both do the same but if you compare with the IL the property would add few extra lines of code to the dll.

The main advantage for me is with readonly you are allowed to declare it anywhere in your code. But, you will get a chance to set it only once. With the setter, you declare and set in one stroke.

Yes, there's a difference between the two.
A readonly field can only be set in the constructor.
A {get; private set;} can be set at anytime from within the class.
Example:
public class Car
{
public readonly string Name;
public string color {get; private set;}
public Car()
{
Name = "Car";
Color = "Red";
}
// will fail compilation
public void ModifyName()
{
Name = "Subaru"
}
// perfectly ok
public void ModifyColor()
{
Color = "Green"
}
}

A Property is just syntactic sugar around a field, a property without a setter is simply declared a readonly field so the compiler will allow you to set it at runtime in the constructor, because to the compiler you are referencing a readonly field. There is a larger discussion around what to use a field or property, which is not within the scope of the question. And yes its this syntactic sugar that you have to do the recompiling referenced by #SOreadytohelp. Just to be clear a property is a field with a get and set method created for it, C# will allow you to reference it like a field rather than doing an annoying call to the getter or setter everytime.

Related

Difference Between readonly field and private getter property

Hello I'm very confused with the difference between a readonly field and a private getter property. I've seen people use both in their code but I simply don't understand what makes them different.
private readonly int num = 0;
// or //
private int Num
{
get { return num; }
}
So is there a difference between using either one of these, or is it by someone's preference?
I'm still beginner in C# & I have some experience with python, so apologies if this is a dumb question. :-)
Getters are usually used to encapsulate access to a field so that implementation logic is hidden from users, making the class more of a black box.
A private getter would only be accesibile to a person implmenting the class (or someone using reflection to access this field) so it wouldn't be useful for encapsulation so much as for implmenting logic in a more convenient way.
A readonly field can only be set in the constructor or field initialiser (which are in both performed in the constructor in the underlying IL), whereas the variable behind a private getter could be set at any time.
A readonly value type is immutable, which means the data held by it in memory will never change once the constructor has executed.
As an example of the difference:
private readonly immutableNum = 0; // this value will be always 0 (unless asigned something else in the constructor
private int num = 0; // this value can be changed anytime by internal logic in the class
private int Num
{
get { Console.WriteLine("Accessed num"); return num; } // additional logic implemented in the getter that can't be done in a readonly field,
//num can be set/reset anytime, so its value can change
}
private immutableGetterNum => 6; //this value will never change
So, do you want to encapsulate access logic? Then you need to use a getter. Do you need to ensure that the value assigned to a field is not changed? Then use a readonly field (or a getter with no underlying field).

C# getter vs readonly

Is there any difference between the following?
class C
{
// One:
public static readonly int ValueAsAMember = 42;
// Two:
public static int ValueAsAProperty { get { return 42; } }
}
I'm used to writing constants the first way (unless they're private/internal, in which case I use the const keyword), but I recently saw the second form.
Is there any advantage one way over the other in terms of readability, convention, performance, or anything else?
You have three choices:
public static readonly int Value = 42;
public static int Value { get { return 42; } }
public const int Value = 42;
Choose static readonly if the value will not change at runtime but might change in future versions of your code.
Choose a property if the value might change at runtime. Of course it won't change if you use the given code.
Choose const if the value is really a constant that will not even change in future versions (something like Math.PI or int.MinValue). And of course the use of const is limited by the type of the value.
The difference between const and static readonly is that the const value will be replaced on the call site. If you change the value of a const in a future version then all assemblies that rely on your class need to be recompiled using the new value.
The property requires a method call (calling a getter is a method call). So if the value is constant at runtime there is no need for that.
Yes, there is an advantage:
If the value gets changeable at any point in the future (e.g. in a future version of your code), in a way that it is, for example, time-dependent, you can support that in the read-only property without changing the public interface of your class.
If you have to replace a readonly field with a property, you will have to recompile any other assemblies that use your class.
There are two major differences:
The first is that fields cannot be on interfaces, whereas properties can. So if you want to use this in an interface, you have to use the property.
The second, more interesting, is that readonly fields CAN be modified, while the object is being constructed. Take the following code:
public class MyTestClass
{
public readonly int MyInt = 1;
public MyTestClass()
{
MyInt = 2;
}
}
If a caller does
new MyTestClass().MyInt
they will get 2. The same goes for static constructors for a static readonly field.
The way I see it, using the first way describes the intention of the value better - which is that it is immutable. When a person is looking at the class' interface, he will see that the value is read-only, and won't have to wonder whether it can be changed later (since in the second case he can't see the property's implementation).
An important thing to note about const declarations (I don't believe it's true for readonly) is that changing the field's value constitutes an API change, even if you're just changing the value from 42 to 41. The reason is that for consts, the value is determined during compile time, which means that if I compile a module that uses your constant, and you later change it, I will still be using the old value until I recompile my module with your new version.
readonly is nice to use on things that can only be changed in your constructor. Examples of this is typical services as interfaces when you are following the TDD pattern.
In your example const is best, it's a constant after all.
readonly
const
Cheers
I think the first line making something constant or rather readonly using readonly keyword.
and the second line is making use of a property to implement readonly. Both do the same but if you compare with the IL the property would add few extra lines of code to the dll.
The main advantage for me is with readonly you are allowed to declare it anywhere in your code. But, you will get a chance to set it only once. With the setter, you declare and set in one stroke.
Yes, there's a difference between the two.
A readonly field can only be set in the constructor.
A {get; private set;} can be set at anytime from within the class.
Example:
public class Car
{
public readonly string Name;
public string color {get; private set;}
public Car()
{
Name = "Car";
Color = "Red";
}
// will fail compilation
public void ModifyName()
{
Name = "Subaru"
}
// perfectly ok
public void ModifyColor()
{
Color = "Green"
}
}
A Property is just syntactic sugar around a field, a property without a setter is simply declared a readonly field so the compiler will allow you to set it at runtime in the constructor, because to the compiler you are referencing a readonly field. There is a larger discussion around what to use a field or property, which is not within the scope of the question. And yes its this syntactic sugar that you have to do the recompiling referenced by #SOreadytohelp. Just to be clear a property is a field with a get and set method created for it, C# will allow you to reference it like a field rather than doing an annoying call to the getter or setter everytime.

How to implement a read only property

I need to implement a read only property on my type. Moreover the value of this property is going to be set in the constructor and it is not going to be changed (I am writing a class that exposes custom routed UI commands for WPF but it does not matter).
I see two ways to do it:
class MyClass
{
public readonly object MyProperty = new object();
}
class MyClass
{
private readonly object my_property = new object();
public object MyProperty { get { return my_property; } }
}
With all these FxCop errors saying that I should not have public member variables, it seems that the second one is the right way to do it. Is this correct?
Is there any difference between a get only property and a read only member in this case?
The second way is the preferred option.
private readonly int MyVal = 5;
public int MyProp { get { return MyVal;} }
This will ensure that MyVal can only be assigned at initialization (it can also be set in a constructor).
As you had noted - this way you are not exposing an internal member, allowing you to change the internal implementation in the future.
C# 6.0 adds readonly auto properties
public object MyProperty { get; }
So when you don't need to support older compilers you can have a truly readonly property with code that's just as concise as a readonly field.
Versioning:
I think it doesn't make much difference if you are only interested in source compatibility.
Using a property is better for binary compatibility since you can replace it by a property which has a setter without breaking compiled code depending on your library.
Convention:
You are following the convention. In cases like this where the differences between the two possibilities are relatively minor following the convention is better. One case where it might come back to bite you is reflection based code. It might only accept properties and not fields, for example a property editor/viewer.
Serialization
Changing from field to property will probably break a lot of serializers. And AFAIK XmlSerializer does only serialize public properties and not public fields.
Using an Autoproperty
Another common Variation is using an autoproperty with a private setter. While this is short and a property it doesn't enforce the readonlyness. So I prefer the other ones.
Readonly field is selfdocumenting
There is one advantage of the field though:
It makes it clear at a glance at the public interface that it's actually immutable (barring reflection). Whereas in case of a property you can only see that you cannot change it, so you'd have to refer to the documentation or implementation.
But to be honest I use the first one quite often in application code since I'm lazy. In libraries I'm typically more thorough and follow the convention.
With the introduction of C# 6 (in VS 2015), you can now have get-only automatic properties, in which the implicit backing field is readonly (i.e. values can be assigned in the constructor but not elsewhere):
public string Name { get; }
public Customer(string name) // Constructor
{
Name = name;
}
private void SomeFunction()
{
Name = "Something Else"; // Compile-time error
}
And you can now also initialise properties (with or without a setter) inline:
public string Name { get; } = "Boris";
Referring back to the question, this gives you the advantages of option 2 (public member is a property, not a field) with the brevity of option 1.
Unfortunately, it doesn't provide a guarantee of immutability at the level of the public interface (as in #CodesInChaos's point about self-documentation), because to a consumer of the class, having no setter is indistinguishable from having a private setter.
In C# 9, Microsoft introduced a new way to have properties set only on initialization using the init accessor, like so:
public class Person
{
public string FirstName { get; init; }
public string LastName { get; init; }
}
This way, you can assign values when initializing a new object:
var person = new Person
{
Firstname = "John",
LastName = "Doe"
}
But later on, you cannot change it:
person.LastName = "Denver"; // throws a compiler error
You can do this:
public int Property { get { ... } private set { ... } }
I agree that the second way is preferable. The only real reason for that preference is the general preference that .NET classes not have public fields. However, if that field is readonly, I can't see how there would be any real objections other than a lack of consistency with other properties. The real difference between a readonly field and get-only property is that the readonly field provides a guarantee that its value will not change over the life of the object and a get-only property does not.
yet another way (my favorite), starting with C# 6
private readonly int MyVal = 5;
public int MyProp => MyVal;
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties#expression-body-definitions
The second method is preferred because of the encapsulation. You can certainly have the readonly field be public, but that goes against C# idioms in which you have data access occur through properties and not fields.
The reasoning behind this is that the property defines a public interface and if the backing implementation to that property changes, you don't end up breaking the rest of the code because the implementation is hidden behind an interface.

More private than private? (C#)

Sometimes you have a private field that backs a property, you only ever want to set the field via the property setter so that additional processing can be done whenever the field changes. The problem is that it's still easy to accidentally bypass the property setter from within other methods of the same class and not notice that you've done so. Is there a way in C# to work around this or a general design principle to avoid it?
IMHO, it is not used, because:
The class must trust itself
If your class gets as large that one part does not know the other, it should be divided.
If the logic behind the property is slightly more complex, consider to encapsulate it in an own type.
I'd consider this a nasty hack and try to avoid it if possible, but...
You can mark the backing field as obsolete so that the compiler will generate a warning when you try to access it, and then suppress that warning for the property getter/setter.
The warning codes that you'd need to suppress are CS0612 for the plain Obsolete attribute and CS0618 if the attribute has a custom message.
[Obsolete("Please don't touch the backing field!")]
private int _backingField;
public int YourProperty
{
#pragma warning disable 612, 618
get { return _backingField; }
set { _backingField = value; }
#pragma warning restore 612, 618
}
There's no inbuilt way to do what you want to do, but by the sounds of things you need another layer of abstraction between your class and that value.
Create a separate class and put the item in there, then your outer class contains the new class, and you can only access it through its properties.
No, there isn't. I'd quite like this myself - something along the lines of:
public string Name
{
private string name; // Only accessible within the property
get { return name; /* Extra processing here */ }
set { name = value; /* Extra processing here */ }
}
I think I first suggested this about 5 years ago on the C# newsgroups... I don't expect to ever see it happen though.
There are various wrinkles to consider around serialization etc, but I still think it would be nice. I'd rather have automatically implemented readonly properties first though...
You CAN do this, by using a closure over a local in the constructor (or other initialisation function). But it requires significantly more work that the helper class approach.
class MyClass {
private Func<Foo> reallyPrivateFieldGetter;
private Action<Foo> reallyPrivateFieldSetter;
private Foo ReallyPrivateBackingFieldProperty {
get { return reallyPrivateFieldGetter(); }
set { reallyPrivateFieldSetter(value); }
}
public MyClass() {
Foo reallyPrivateField = 0;
reallyPrivateFieldGetter = () => { return reallyPrivateField; }
reallyPrivateFieldSetter = v => { reallyPrivateField = v; };
}
}
I suspect that the underlying field type Foo will need to be a reference class, so the two closures are created over the same object.
There is no such provisioning in C#.
However I would name private variables differently (e.g. m_something or just _something) so it is easier to spot it when it is used.
You can put all of your private fields into a nested class and expose them via public properties. Then within your class, you instantiate that nested class and use it. This way those private fields are not accessible as they would have been if they were part of your main class.
public class A
{
class FieldsForA
{
private int number;
public int Number
{
get
{
//TODO: Extra logic.
return number;
}
set
{
//TODO: Extra logic.
number = value;
}
}
}
FieldsForA fields = new FieldsForA();
public int Number
{
get{ return fields.Number;}
set{ fields.Number = value;}
}
}
It just provides a level of obstruction. The underlying problem of accessing private backing fields is still there within the nested class. However, the code within class A can't access those private fields of nested class FieldForA. It has to go through the public properties.
Perhaps a property backing store, similar to the way WPF stores properties?
So, you could have:
Dictionary<string,object> mPropertyBackingStore = new Dictionary<string,object> ();
public PropertyThing MyPropertyThing
{
get { return mPropertyBackingStore["MyPropertyThing"] as PropertyThing; }
set { mPropertyBackingStore["MyPropertyThing"] = value; }
}
You can do all the pre-processing you want now, safe in the knowledge that if anyone did access the variable directly, it would have been really really hard compared to the property accessor.
P.S. You may even be able to use the dependency property infrastructure from WPF...
P.P.S. This is obviously going to incur the cost of casting, but it depends on your needs - if performance is critical, perhaps this isn't the solution for you.
P.P.P.S Don't forget to initialise the backing store! (;
EDIT:
In fact, if you change the value property stored to a property storage object (using the Command pattern for example), you could do your processing in the command object...just a thought.
Can't do this in standard C#, however you could
define a custom attribute say OnlyAccessFromProperty
write your code like
[OnlyAccessFromProperty(Name)]
String name
Name
{
get{return name;}
}
etc …
Then write a custom rule for FxCop (or another checker)
Add FxCop to your build system so if your custom rule find an error the build is failed.
Do we need a set of standard custom rules/attributes to enforce common design patens like this without the need to extend C#
C# has no language feature for this. However, you can rely on naming conventions, similar to languages which have no private properties at all. Prefix your more private variable names with _p_, and you'll be pretty sure that you don't type it accidentally.
I don't know C# but in Java you may have a base class with only private instance variables and public setters and getters (should return a copy of the instance var.) and do all other in an inherited class.
A "general design principle" would be "use inheritance".
There is no build in solution in C#, but I think your problem can be solved by good OO design:
Each class should have a single purpose. So try to extract the logic around your field into a class as small as possible. This reduces the code where you can access the field by accident. If you do such errors by accident, your class is probably to big.
Often interface are good to restrict access to only a certain "subset" of an object. If that's appropriate for your case depends on your setting of course. More details about the work to be done would help to provide a better answer.
You say that you do additional processing. Presumably this would be detectable under the correct conditions. My solution, then, would be to create unit tests that implement conditions such that if the backing field is used directly the test will fail. Using these tests you should be able to ensure that your code correctly uses the property interface as long as the tests pass.
This has the benefit that you don't need to compromise your design. You get the safety of the unit tests to ensure that you don't accidently make breaking changes and you capture the understanding of how the class works so that others who come along later can read your tests as "documentation."
Wrap it in a class? The property thing is a bit like that anyway, associating data with methods - the "Encapsulation" they used to rave about...
class MyInt
{
private int n;
public static implicit operator MyInt(int v) // Set
{
MyInt tmp = new MyInt();
tmp.n = v;
return tmp;
}
public static implicit operator int(MyInt v) // Get
{
return v.n;
}
}
class MyClass
{
private MyInt myint;
public void func()
{
myint = 5;
myint.n = 2; // Can't do this.
myint = myint + 5 * 4; // Works just like an int.
}
}
I'm sure I'm missing something? It seems too normal...
BTW I do like the closures one, superbly mad.
My favorite solution to this (and what I follow) is to name private backing fields that are never intended to be used directly with a leading underscore, and private fields that are intended to be used without the underscore (but still lowercase).
I hate typing the underscore, so if I ever start to access a variable that starts with the underscore, I know somethings wrong - I'm not supposed to be directly accessing that variable. Obviously, this approach still doesn't ultimately stop you from accessing that field, but as you can see from the other answers, any approach that does is a work around and/or hardly practical.
Another benefit of using the underscore notation is that when you use the dropdown box to browse your class, it puts all of your private, never-to-be-used backing fields all in one place at the top of the list, instead of allowing them to be mixed in with their respective properties.
As a design practice, you could use a naming convention for "private properties" that's different from normal public members - for instance, using m_ItemName for private items instead of ItemName for public ones.
If you're using the C# 3.0 compiler you can define properties which have compiler-generated backing fields like this:
public int MyInt { get; set; }
That will mean there is only one way to access the property, sure it doesn't mean you can only access the field but it does mean that there's nothing but the property to access.
I agree with the general rule that the class should trust itself (and by inference anybody coding within the class).
It is a shame that the field is exposed via intellisense.
Sadly placing [EditorBrowsable(EditorBrowsableState.Never)] does not work within that class (or indeed the assembly(1))
In Visual C#, EditorBrowsableAttribute does not suppress members from a class in the same assembly.
If you really do wish to solve this aspect of it the the following class may be useful and makes the intent clear as well.
public sealed class TriggerField<T>
{
private T data;
///<summary>raised *after* the value changes, (old, new)</summary>
public event Action<T,T> OnSet;
public TriggerField() { }
///<summary>the initial value does NOT trigger the onSet</summary>
public TriggerField(T initial) { this.data=initial; }
public TriggerField(Action<T,T> onSet) { this.OnSet += onSet; }
///<summary>the initial value does NOT trigger the onSet</summary>
public TriggerField(Action<T,T> onSet, T initial) : this(onSet)
{
this.data=initial;
}
public T Value
{
get { return this.data;}
set
{
var old = this.data;
this.data = value;
if (this.OnSet != null)
this.OnSet(old, value);
}
}
}
Allowing you to (somewhat verbosely) use it like so:
public class Foo
{
private readonly TriggerField<string> flibble = new TriggerField<string>();
private int versionCount = 0;
public Foo()
{
flibble.OnSet += (old,current) => this.versionCount++;
}
public string Flibble
{
get { return this.flibble.Value; }
set { this.flibble.Value = value; }
}
}
alternatively you can go for a less verbose option but accessing Flibble is by the not idiomatic bar.Flibble.Value = "x"; which would be problematic in reflective scenarios
public class Bar
{
public readonly TriggerField<string> Flibble;
private int versionCount = 0;
public Bar()
{
Flibble = new TriggerField<string>((old,current) => this.versionCount++);
}
}
or solution if you look at the community content!
The new Lazy class in .net 4.0
provides support for several common
patterns of lazy initialization
In my experience this is the most common reason I wish to wrap a field in a private properly, so solves a common case nicely. (If you are not using .Net 4 yet you can just create your own “Lazy” class with the same API as the .Net 4 version.)
See this and this and this for details of using the Lazy class.
Use the "veryprivate" construct type
Example:
veryprivate void YourMethod()
{
// code here
}

Should I use public properties and private fields or public fields for data?

In much of the code I have seen (on SO, thecodeproject.com and I tend to do this in my own code), I have seen public properties being created for every single private field that a class contains, even if they are the most basic type of get; set; like:
private int myInt;
public int MyInt
{
get { return myInt; }
set { myInt = value }
}
My question is: how does this differ from:
public int MyInt;
and if we should use properties instead of public fields why should we use them in this specific case? (I am not talking about more complex examples where the getters and setters actually do something special or there is only one get or set (read/write only) rather than just returning/setting a value of a private field). It does not seem to add any extra encapsulation, only give a nice icon in IntelliSense and be placed in a special section in class diagrams!
See this article http://blog.codinghorror.com/properties-vs-public-variables/
Specifically
Reflection works differently on variables vs. properties, so if you rely on reflection, it's easier to use all properties.
You can't databind against a variable.
Changing a variable to a property is a breaking change.
Three reasons:
You cannot override fields in subclasses like you can properties.
You may eventually need a more complex getter or setter, but if it's a field, changing it would break the API.
Convention. That's just the way it's done.
I'm sure there are more reasons that I'm just not thinking of.
In .Net 3.x you can use automatic properties like this:
public int Age { get; set; }
instead of the old school way with declaring your private fields yourself like this:
private int age;
public int Age
{
get { return age; }
set { age = value; }
}
This makes it as simple as creating a field, but without the breaking change issue (among other things).
When you create private field name and a simple public property Name that actually gets and sets the name field value
public string Name
{
get { return name; }
}
and you use this property everywhere outside your class and some day you decide that the Name property of this class will actually refer to the lastName field (or that you want to return a string "My name: "+name), you simply change the code inside the property:
public string Name
{
get { return lastName; //return "My name: "+name; }
}
If you were using public field name everywhere in the outside code then you would have to change name to lastName everywhere you used it.
Well it does make a difference. Public data can be changed without the object instance knowing about it. Using getters and setters the object is always aware that a change has been made.
Remember that encapsulating the data is only the first step towards a better structured design, it's not an end-goal in itself.
You have to use properties in the following cases:
When you need to serialize data in the property to some format.
When you need to override properties in derived class.
When you implement get and set methods with some logic. For example, when you implement Singleton pattern.
When you're derived from interface, where property was declared.
When you have specific issues related to Reflection.
It... depends?
I always use getters & setters, since they created this shortcut:
public int Foo { get; set; }
At compile time it is translated. Now you can't get fancy with it, but it is there, and if you need to get fancy you just spell it out later.
However public, private, protected... it's all a matter of who you want to be able to tweak the data. We use inheritance a lot and this is a very common method for us, so that only chidren can edit certain properties.
protected _foo;
public Foo
{
get { return _foo; }
} //lack of set intentional.
I can't believe that with 11 answers, nobody has said this:
Not all private fields should be exposed as public properties. You should certainly use properties for anything that needs to be non-private, but you should keep as much of your class private as possible.
There are many reasons why.
Mainly:
You can do some other functions when the variable is set
You can prevent setting and provide only get
Some 'things' only work on properties (DataBinding, for example)
You can hide the implementation of the property [perhaps it is a ViewState variable, in ASP.NET).
The point is - what if further down the line you want to make sure that every time myInt is referenced something special happens (a log file is written to, it's changed to 42 etc)? You can't do that without getters and setters. Sometimes it's wise to program for what you might need, not what you need right now.
Actually, if you're using Silverlight, you'll realise that fields cannot be set a static resources and thus you'll have to use a property (even to access a const).
I've realised that when I tried to federate the region names I use in Composite Guidance (PRISM).
However, that's just a language limitations and apart from static/const fields I alsways use properties.
The idea is you should not accidentally/unintentionally change the value of a class private field outside.
When you use get and set, that means you are changing the class private field intentionally and knowingly.
Setting a value into a private field only changes that field,but making them in property you can handle another arguments for example,you can call a method after setting a value
private string _email;
public string Email
{
get
{
return this._email;
}
set
{
this._email = value;
ReplaceList(); //**
}
}
In simpler words, answer to your question is the access modifiers i.e. public and private.
If you use:
public int myInt;
public int MyInt
{
get { return myInt; }
set { myInt = value }
}
then both MyInt property and myInt variable is available in the project to be modified.
Means, if your class suppose A is inherited by class suppose B,
then myInt and MyInt both are available for modification and no check can be applied.
Suppose you want myInt value can be set in derive class if some particular condition pass.
This can be achieved only by making field private and property to be public.
So that only property is available and conditions can be set based on that.

Categories

Resources