Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encapsulation C# newbie

New to C#, and I understand that encapsulation is just a way of "protecting data". But I am still unclear. I thought that the point of get and set accessors were to add tests within those methods to check to see if parameters meet certain criteria, before allowing an external function to get and set anything, like this:

private string myName;
public string MyName;// this is a property, speical to c#, which sets the backing field.

private string myName = "mary";// the backing field.

public string MyName // this is a property, which sets/gets the backing field.
{
    get
    {
        return myName;
    }
    set
    {
        if (value != "Silly Woman"){ 
           myName = value;
        }

    } 
}

But I've been seeing code in c# which just looks like this:

public string MyName { get; set; }

Why would you just have a get and set with nothing in there, - isn't that the same as just declaring your private backing field public? If you can just get and set it from outside, why wouldn't you just do it directly?

like image 581
Gia Sadhwani Avatar asked Jul 16 '13 02:07

Gia Sadhwani


People also ask

Can we do encapsulation in C?

It is one of the core features of Object-oriented languages. However, it is not only limited to OOP languages only. In C, encapsulation has been despite the absence of private and public keywords. Encapsulation is being used by various other programming languages like C#, C++, PHP, JAVA as well.

What is encapsulation and abstraction in C?

Abstraction is the method of hiding the unwanted information. Whereas encapsulation is a method to hide the data in a single entity or unit along with a method to protect information from outside. 4. We can implement abstraction using abstract class and interfaces.

What is meant by the encapsulation?

Encapsulation is a way to restrict the direct access to some components of an object, so users cannot access state values for all of the variables of a particular object. Encapsulation can be used to hide both data members and data functions or methods associated with an instantiated class or object.


1 Answers

Indeed, creating an auto-property as follows:

public string Name { get; set; }

is identical to building a property backed by a field:

private string _name;
public string Name {
    get { return _name; }
    set { _name = value; }
}

The point of these properties is not to hide data. As you observed, they don't do this. Instead, these properties can do other stuff instead of just working with a field:

public string Name {
    get { return _name; }
    set { if (value == null) throw new Exception("GTFO!"); _name = value; }
}

Another thing is, you can make properties virtual:

public virtual string Name { get; set; }

which, if overridden, can provide different results and behaviours in a derived class.

like image 172
CSJ Avatar answered Oct 20 '22 00:10

CSJ