How do access modifiers help in get;set;? - c#

I need a in-depth answer to this question. How are these three int different from each other?
class whatever{
private int a {get; set;}
private int b {public get; private set;}
private int c {private get; public set;}
}
I would really appreciate it if I am provided with some code to experiment it in VS Community.
And do tell me that by not providing access providers at all, what happens? (As in the case of int a)

In C# 1.0, you could only put one access modifier on the entire property.
(There also weren't auto-implemented properties yet)
private int status;
public int Status {
get { return status; }
set { status = value; }
}
means that both the getter and setter are public, because the property is public.
In C# 2.0, they thought it might be helpful to have different modifiers for the getter and the setter, so they made it so that you can 'override' one of the accessors. There are certain rules, for instance the overridden one has to be more restrictive than the modifier of the property itself.
The following example means the getter is public (because the property has the public modifier) and the setter is private, because it has been overridden.
private int status;
public int Status {
get { return status; }
private set { status = value; }
}
So you can say Status = 2; from within the class, but you can no longer call it from outside the class.
Why didn't they make it like the following?
private int status;
int Status {
public get { return status; }
private set { status = value; }
}
Because that would break backward compatibility. The C# 1.0 example will still have to compile in the new version. When you introduce new features to a language, you have to make choices. This is the one they made.
And of course, in C# 3.0, we got auto-implemented properties, which made our lives a lot easier:
public int Status { get; private set; }
However, this is not truly a readonly property. For that, we had to wait for C# 6.0:
public int Status { get; } = 5;

Related

How to prevent direct access to the variable in a class?

In my class I have private variable, which I use inside the class only through get/set. Sometimes I forget, that I shouldn't use variable directly (even within the class) and must use get/set.
How to make that the only way to use a variable were get/set?
public class A {
int x;
public XVariable {
get { return x; }
set { x = value }
// some additional operations
}
void SomeMethod() {
x = 5; // no
XVariable = 5; // yes
}
}
C# has auto properties. No backing field needed in your code.
public class A {
public XVariable {
get;
set;
}
}
You can also have different access modifiers. Like if you want to only be able to set it from within the class.
public class A {
public XVariable {
get;
private set;
}
}
There won't be a backing field accessible from your code, but the compiler will generate one in the MSIL (what C# compiles to). You don't have to worry about that part though.
A potential downside Joe pointed out to auto props, sometimes you need to perform other actions (especially event handlers) in your property when you set something. But that's not possible with auto props. In that case, his answer would be more appropriate. But if that's not a concern for your use case, then my answer should be sufficient.
You can create a base class, and do all your real work in the derived class:
public class SomeBaseClass {
private int _x;
public int X { get { return _x; } set { _x = value; } }
}
public class DerivedClass : SomeBaseClass {
void DoSomething() {
// Does not have access to _x
}
}
Many people prefix their private variables with an underscore to help signify the variable is private. (Although it is a matter of opinion, some people like it and some don't) There is a bit more insight on this question.
You can however, scrap the field and use an auto property such as:
public XVariable { get; set; }
An auto property will store an anonymous backing field "out of view".

How to access private variables using { get; set; }

I'd like to create a class for my website with a lot of private variable.
I thought there was a solution not to write all the getters and setters for each variable, something like
private int confirmed { get; set; }
Is it the right way? ANd then, how do I access this value from outside the class?
I've tried .confirmed , I get the error saying that it's private (which I understand)
But more surprising, .getConfirmed() or getconfirmed() do not work either.
I thought that the { get; set; } would create implicitely those methods.
Can someone clarify this concern for me please?
You can declare your property as public, then mark the getter or setter individually as private:
public int confirmed { get; private set; }
That way, you can access confirmed outside of your defined class:
Console.WriteLine(myClass.confirmed); // This is OK
myClass.confirmed = "Nothing"; // Can't do this
And the only one who can set the value of confirmed is then MyClass:
public class MyClass {
public int confirmed { get; private set; }
public MyClass() {
this.confirmed = "This"; // This is fine as we have private access
}
}
You need to understand that,
private int confirmed { get; set; }
will be expanded to a set of private methods with a private backing field,
private int _confirmed;
private int confirmed_get()
{
return this._confirmed;
}
private void confirmed_set(int value)
{
this._confirmed = value;
}
Thus, marking the property private makes both the accessor and the mutator also private, which is why you cannot access them outside of the class. Also, these methods are not accessible at compile time, so calling instance.confirmed_get() is not permitted, only instance.confimed both to read and write to the property.
What you might want is to declare it public,
public int confirmed { get; set; }
where the behavior is similar (the field still is private), but both method are now public. As others have mention you can individually modify the get and set for readonly or writeonly type of behavior,
public int confirmed { get; private/protected set; }
or
public int confirmed { private/protected get; set; }
And one last thing, you should get into the habit of using camel case for propeties, e.g. Confirmed and lower camel case for fields, e.g. confirmed (some might even do _confirmed). It is a popular naming conventions to distinguish the two types, especially for consumers of the class.
how do I access this value from outside the class?
You can't (without reflection form trusted code). They're private. If you want the getter to be public but the setter private then do
public int confirmed { get; private set; }
I thought that the {get;set;} would create implicitly those methods.
It does, but they're not accessible at design time.
Just do this if you want to get it from outside the class.
public int confirmed { get; set; }
or you can go this route:
private int confirmed;
public int Confirmed
{
get { return confirmed }
set { confirmed = value; }
}
There are multiple ways to perform such action. Depending upon your requirements, you can choose any one method from below:
// Old Conventional - Statement body
public class SampleClass1
{
public bool CanAccessFromOutside
{
get { return _cannotAccessFromOutside; }
}
private bool _cannotAccessFromOutside;
private void DoSomething()
{
_cannotAccessFromOutside = true;
}
}
// Expression Bodied Property
public class SampleClass2
{
public bool CanAccessFromOutside => _cannotAccessFromOutside;
private bool _cannotAccessFromOutside;
private void DoSomething()
{
_cannotAccessFromOutside = true;
}
}
// Auto Property
public class SampleClass3
{
public bool CanAccessFromOutside { get; private set; }
private void DoSomething()
{
CanAccessedFromOutside = true;
}
}

C# basic property understanding

I am learning C# and i have encounter the following piece of code
public class Album
{
public virtual int AlbumId { get; set; }
public virtual int GenreId { get; set; }
public virtual int ArtistId { get; set; }
public virtual string Title { get; set; }
public virtual decimal Price { get; set; }
public virtual string AlbumArtUrl { get; set; }
public virtual Genre Genre { get; set; }
public virtual Artist Artist { get; set; }
}
just wondering what's the different with the following? i mean without the get and set you can access those public property as well. what's make it important to have those get and set?
public class Album
{
public virtual int AlbumId;
public virtual int GenreId;
public virtual int ArtistId;
public virtual string Title;
public virtual decimal Price;
public virtual string AlbumArtUrl;
public virtual Genre Genre;
public virtual Artist Artist;
}
To have control over your object private fields values. for example if you don't wanna allow nulls or negative values for integers.
bool started;
public bool Started
{
get { return started; }
set
{
started = value;
if (started)
OnStarted(EventArgs.Empty);
}
}
another example
int positiveNumber;
public int PositiveNumber
{
get { return positiveNumber; }
set {
if (value < 0)
positiveNumber = 0;
else positiveNumber = value;
}
}
and also another implementation of read only properties could be as follows
int positiveNumber;
public int PositiveNumber
{
get { return positiveNumber; }
}
You can't declare a virtual field
public class Album
{
public virtual int AlbumId; // <- Syntax error
...
}
properties are, in fact, methods: get or(and) set, so
public class Album
{
public virtual int AlbumId { get; set; } // <- Both get and set methods declared as virtual ones
...
}
And you can override these get's or(and) set's in derived class if you want:
public class GreatAlbum: Album {
private Boolean m_IsGreat;
public override int AlbumId {
get {
if (m_IsGreat)
return base.AlbumId
else
return 0;
}
set {
m_IsGreat = (value != 0);
base.AlbumId = value;
}
}
...
}
With providing get(accessor) and set(mutator) methods, you can control accessing and mutating.
For example:
You have a property that you don't want to be set any value more than 15. So u make required restrictions in your set method. Unless that set method, you can't control.
But in your example, your get and set methods are default, means controlling nothing.
The main reason behind properties is to protecting and presenting private data in a controlled way.
In fact, properties show their abilties in the usage like this:
public virtual int AlbumId
{
get { // ... some magical operations ... }
set { // ... some magical operations ... }
}
And about your main question - what's the difference in this example - the main point to attention is the virtual keyword.
This keyword causes the property to be overrideable, So any other code could override the default get; method. It meens that you have the default behavior for yourself, and other codes (Extremely used in Entity Framework) implement their own logic!
Those second ones in your example aren't properties, so they don't express this magical ability...!
In the first case you are dealing with properties, in the second with fields.
Using fields has several drawbacks when compared to using properties. These drawbacks include:
You can set a breakpoint in a get or set of a property, but you can not set a breakpoint on access to the field.
Making fields public violates the information hiding principle.
The binary MSIL code for accessing fields and properties is different, so if you change a public field to a public property in the future, although the source code stays compatible, any dependant binary code breaks.
The code required to use reflection is different, hence when you move from a field to a property, your reflection code will break.
To cut a long story short: Always use public properties, NEVER use public fields.
There are a number of differences:
Properties are turned into methods by the compiler. As such, you can declare them virtual and override them in a derived class.
Using properties, you can put logic in the getter or setter (filtering, validation etc).
When you use automatically implemented properties ({ get;set;}), it may seem that you might as well just use public fields. However, using properties means you can change your getter or setter implementation at a later time, without changing the interface your class is exposing. If you had used a field and wanted to implement filtering whenever that field was read, you would have to introduce a new method, make the field private and break all existing consumers of the type.
Personally, I think the automatically implemented properties promote bad style, because they do not encourage encapsulation. Tools like ReSharper also like to generate properties with {get;set} accessors. Novice developers thus typically end up with classes with lots of {get;set;} properties exposing the type's state to the world. You should at least use {get; private set;} by default.

How to make a field read only outside class

I have the following class (example):
public class Dog
{
int numberOfTeeth;
public Dog()
{
countTeeth();
}
private void countTeeth()
{
this.numberOfTeeth = 5; //this dog has seen better days, apparently
}
}
After I create the dog object, it should have the number of teeth calculated. I'd like to be able to access that value without being able to modify it outside the class itself.
Dog d = new Dog();
int dogTeeth = d.numberOfTeeth; //this should be possible
d.numberOfTeeth = 10; //this should not
However, I can't figure out which access modifier will let me do this. I've tried all of the following:
If I make numberOfTeeth private, I cannot access it.
If I make numberOfTeeth protected internal, I can change this value outside the class.
If I make numberOfTeeth internal, I can change this value outside the class.
If I make numberOfTeeth protected, I cannot access it.
If I make numberOfTeeth public, I can change this value outside the class.
I also tried making it readonly but then was unable to set it outside the constructor.
Is there any access modifier which will allow me to do this? Or is there some other method of accomplishing this protection?
Create a property with a private setter:
public int NumberOfTeeth
{
get; private set;
}
Notice I changed it to Pascal Case to match most .NET style standards.
You can't do that. You can make the field read-only and make a method that returns its value. You can also make an auto-property with a public getter and a protected setter:
public int NumberOfTeeth { get; protected set; }
You should make the field private and create a read-only (no setter) public property:
public class Dog
{
private int numberOfTeeth;
public int NumberOfTeeth {get {return numberOfTeeth;}}
public Dog()
{
countTeeth();
}
private void countTeeth()
{
this.numberOfTeeth = 5; //this dog has seen better days, apparently
}
}
public class Dog
{
public int numberOfTeeth { get; private set; }
public Dog()
{
countTeeth();
}
}

Covariance, Contravariance and Delegate Problem

I again need help by you, this time I struggle with covariance, contravariance, delegates and an simple idea blowing up...
I want to implement an attribute for our businessobject-properties that takes a delegate and the needed parameters for that one, so that I can work with reflection, read out the attribute and perform a validation on the property value.
The reason behind this is, we are using Windows.Forms with DataBinding and need to set the DataBinding update method to OnPropertyChanged, to get a properly working refresh on the GUI.
We do need however a way to react in the validating-events of the controls to validate the property correctly, to see if the user can actually e.g. save the object. But the Validating-Event of the control occurs only after writing the value to the property. Having a validation in the setter of the property would cause a crash and we could not provide the user exact information what is wrong unless we implement the validation a second time (or extract it to a method called from the setter).
To keep this most elegant and clean, I thought one of the following would be nice to have:
[PropertyValidator(ValidationHelper.ValidateString, new StringValidatorArgs(true, 3, 15))]
That way I could iterate via reflection over all properties, perform all validations we want them to and set a PropertyValidator-Attribute for with the correct Method. But I played with the idea a bit and do not get this anyway to work, here is what I have, might be you have an idea about how to achive this.
public delegate bool Validator(object validatee, ValidatorArgs v);
public class ValidatorArgs
{
}
public class StringValidatorArgs : ValidatorArgs
{
public StringValidatorArgs(bool nullCheck, int minLength, int maxLength)
{
this.NullCheck = nullCheck;
this.MinLength = minLength;
this.MaxLength = maxLength;
}
public bool NullCheck { get; set; }
public int MinLength { get; set; }
public int MaxLength { get; set; }
}
public class MyClass
{
[PropertyValidator(ValidationHelper.ValidateString, new StringValidatorArgs(true, 3, 15))]
public string MyString { get; set; }
}
public static class ValidationHelper
{
public static bool ValidateString(object validatee, StringValidatorArgs v)
{
return true;
}
}
[AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = true)]
public class PropertyValidatorAttribute
: Attribute
{
#region Constructor
private PropertyValidatorAttribute()
{
}
public PropertyValidatorAttribute(Validator validator, ValidatorArgs args)
{
this.Validator = validator;
this.Args = args;
}
#endregion
#region Properties
public Validator Validator
{
get;
private set;
}
public ValidatorArgs Args
{
get;
private set;
}
#endregion
}
Any hints welcome...
What about implementing IDataErrorInfo to provide validation information from your object, instead of (I'm assuming) throwing an exception from the setter on bad data? Most Windows Forms controls are IDataErrorInfo savvy, and will provide corresponding UI validation information on a per-property or per-object basis.

Categories