How to access private variables using { get; set; } - c#

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;
}
}

Related

Get property path from property instance

Say we have some code like this:
public class FeatureAnalysis
{
private float errorLevel;
public float ErrorLevel
{
get { return errorLevel; }
set
{
this.errorLevel = value;
// Something here?
}
}
public int MeasurementTime { get; set; }
}
public class TestStep
{
public FeatureAnalysis FeatureAnalysis { get; set; }
}
public class Test
{
public TestStep TestStep { get; set; }
}
Suppose we have another class that has a member of type Test. I know it is possible to get the value from ErrorLevel using a string like this "TestStep.FeatureAnalysis.ErrorLevel". (I call it the propertypath, don't know if this is the correct term though). The problem I'm facing seems to require to build this string somehow.
We would like to log changes to every property that is somehow under the Test class, or its members, or its members, ... So the path should go up to Test and no further. I'm also thinking of situations where we have "TestStep.FeatureAnalysis[0].ErrorLevel"
I'm hoping that we don't have to pass the 'parent path' all over.
Alternative ideas are more than welcome.

How do access modifiers help in get;set;?

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;

What difference does this `private set` make within this immutable class

I'm studying this simple class and wondering what difference the private set of the Name property actually makes?
If that line simply read public string Name { get; } how would the user's interaction with the class change?
public class Contact2
{
// Read-only properties.
public string Name { get; private set; }
public string Address { get; }
// Private constructor.
private Contact2(string contactName, string contactAddress)
{
Name = contactName;
Address = contactAddress;
}
// Public factory method.
public static Contact2 CreateContact(string name, string address)
{
return new Contact2(name, address);
}
}
They are both read-only properties, and objects of this class can only be constructed via the static method, so does it matter if the set of name is private or not?
EDIT
It is part of this MSDN code:
https://msdn.microsoft.com/en-us/library/bb383979.aspx
In C# 6:
public string Name { get; private set; }
Can be set from any method within the class.
public string Address { get; }
Is a read-only property and can only (and must) be set on initialization.
In your code they're functioning the same way, however the read-only property enforces an additional constraint making the property immutable as it can only be set once, whereas you could add a method to the class which mutates Name making the class mutable.
Getter-only auto properties like public string Name { get; } were not allowed before C# 6.0, so the code would not compile. That's why you needed a private setter before.
See: Getter-only auto-properties.

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.

Why isn't the most specific method called based on type of parameter

Total OO noob question here. I have these two methods in a class
private void StoreSessionSpecific(LateSession dbSession, SessionViewModel session)
{
session.LateSessionViewModel.Guidelines = dbSession.Guidelines.ToList();
}
private void StoreSessionSpecific(Session dbSession, SessionViewModel session )
{
// nothing to do yet...
}
And when I call StoreSessionSpecific with dbSession being of type LateSession (LateSession inherits Session)
var dbSession = new LateSession();
StoreSessionSpecific(dbSession, session);
I expected the top one to be called. Since dbSession is of type LateSession.
#Paolo Tedesco This is how the classes are defined.
public class Session
{
public int ID { get; set; }
public int SessionTypeId { get; set; }
public virtual SessionType SessionType { get; set; }
[Required]
public DateTime StartTime { get; set; }
[Required]
public DateTime EndTime { get; set; }
// Session duration in minutes
// public int SessionDuration { get; set; }
public virtual ICollection<Attendee> Attendees { get; set; }
}
public class LateSession : Session
{
public int MaxCriticalIncidentsPerUser { get; set; }
public int MaxResultCriticalIncidents { get; set; }
public virtual ICollection<Guideline> Guidelines { get; set; }
}
Well, your assumption is plausible and there are languages where it had worked like you thought.
So does your code look like this:
Session s = new LateSession(); // the compiler only "knows" that s is of type Session
StoreSessionSpecific(s);
or does it look like this:
LateSession ls = new LateSession(); // the compiler knows that ls is in fact a LateSession
StoreSessionSpecific(ls);
In the first example the compiler prettends not to know what the actual type of "s" is and hard codes the invocation of the method with the Session argument.
In the second example likewise the compiler generates a hard coded call to the other method.
In other languages the method call is "dynamic", that means during runtime the actuall types are considered. Methods that are polymorphic on their arguments are called "multimethods" (They are not only polymorphic on the class they are defined in but also on the arguments, hence "multi")
(Edit: fixed typos)
I think the problem is somewhere else in your code. If you try this example, things work as expected:
class Base {
}
class Derived : Base {
}
class Something {
private void DoSomething(Base b) {
Console.WriteLine("DoSomething - Base");
}
private void DoSomething(Derived d) {
Console.WriteLine("DoSomething - Derived");
}
public void Test() {
var d = new Derived();
DoSomething(d);
}
}
static class Program {
static void Main(params string[] args) {
Something something = new Something();
something.Test();
}
}
Could you post a complete example? maybe there's a problem with the class definitions...
I apologize for not knowing the specifics of why this happens, but I have an idea on how to work around it.
Try loosing the (LateSession, SessionViewModel) overload, and account for LateSession in the (Session, SessionViewModel) overload like:
private void StoreSessionSpecific(Session dbSession, SessionViewModel session )
{
if (dbSession is LateSession) {
// handle as LateSession
} else {
// handle as base-class Session
}
}
As Angel O'Sphere said, C# doesn't have multiple dispatch however you can implement double dispatch using Visitor Pattern.
http://en.wikipedia.org/wiki/Visitor_pattern
What is the type of dbSession after that assignment? I would assume it is what you expect, but it could be a Session.
Separately, do you really need to overload this method with both a child and parent class? It seems like a strange case where you would need both, and will likely lead to confusion.

Categories