Sign in to follow this  
GraySnakeGenocide

Need help understanding Encapsulation, Properties and Fields in C#

Recommended Posts

I have no idea how to use these, or even what they are used for exactly.

I have a million books, all of which I've looked at, I looked at a bunch of YT tutorials, still don't understand

As far as I understand, Fields are like, variables specific to a class or something.

And Properties are sort of like methods. The Get/Set accessor things have me scratching my head as well.

Basically, can someone explain to me in the most basic way, how to use Fields, and how to use Properties with the Get/Set accessors?

As for Encapsulation, all I know is that it's a way of keeping data hidden within a class. Only problem is, what is it used for exactly? I'm not sure what encapsulations purpose is.

Sorry in advance if some of these questions aren't worded good/the questions overall are silly, I am just about to head to bed.

Share this post


Link to post
Share on other sites
Telastyn    3777
[b]Classes [/b]represent a cohesive concept. Concepts have data that represent their state or configuration, and methods that perform some action or change the state/configuration.

[b]Fields [/b]represent that state or configuration that is required by your class to do... whatever it's doing.
[b]Properties [/b]behave like fields, but (unless they're auto properties) [i]don't actually store anything[/i]. They simply provide state or configuration that you can calculate some other manner.

If you have a class that represents a rectangle for example, you don't need to [i]store[/i] the area of the rectangle. You can store the width and height, and then provide Area as a [b]property[/b], calculated from the other two fields. The get/set accessors are the means for you to specify how to map the property to 0 or more fields.


Encapsulation is used to keep a class behaving as it should. Concepts often have [b]invariants[/b]. [b]Invariants[/b] are... rules essentially that a class must follow. For the sake of example (don't do this in the real world) we wanted a class that was a square. While it has a width and a height, is has the [b]invariant[/b] that width and height always be equal. If you just supply width and height as public fields, someone could go in and make the width different from the height. Instead you would keep that storage private, and provide properties or methods that perform actions on the class while maintaining that class requirement. A more practical benefit is that the fewer things that can modify a field, the easier it is to then debug your program when the field ends up with the wrong value somehow.

Share this post


Link to post
Share on other sites
DarrenHorton    110
Very good question. I too am having big problems coding anything at the moment.

I try to make a few classes and have the bullets shooting from the ship but no joy.

I get null reference errors, variables changing values etc

I try to code to take a break from theory study.

I have been learning for a month, but not much has sunk in cos reading code is a bit of a dry subject to me.

Don't tell me it's not either!

Here's a decent website for beginners. [url="http://www.csharp-station.com/default.aspx"]http://www.csharp-station.com/default.aspx[/url]

Share this post


Link to post
Share on other sites
Serapth    6671
[quote name='blackbook' timestamp='1307299134' post='4819822']
I have been learning for a month, but not much has sunk in cos reading code is a bit of a dry subject to me.

Don't tell me it's not either!
[/quote]


This depends on the person and perhaps the level of experience they have.

Frankly, reading other peoples code, especially finely crafted code can be a similar experience to watching a great moving or reading an expertly written book. At times it can be an inspiring and informative experience.

On the flipside though, reading "abstract" teaching code, code written to teach a language feature as opposed to actually "doing" something... like code showing inheritance using classes A, B and C, this is horrifically painful for me to read! It's as much how my brain is wired, but purposeless code is horrifically difficult for me to grok.


Share this post


Link to post
Share on other sites
[quote name='Telastyn' timestamp='1307290534' post='4819786']
[b]Classes [/b]represent a cohesive concept. Concepts have data that represent their state or configuration, and methods that perform some action or change the state/configuration.

[b]Fields [/b]represent that state or configuration that is required by your class to do... whatever it's doing.
[b]Properties [/b]behave like fields, but (unless they're auto properties) [i]don't actually store anything[/i]. They simply provide state or configuration that you can calculate some other manner.

If you have a class that represents a rectangle for example, you don't need to [i]store[/i] the area of the rectangle. You can store the width and height, and then provide Area as a [b]property[/b], calculated from the other two fields. The get/set accessors are the means for you to specify how to map the property to 0 or more fields.


Encapsulation is used to keep a class behaving as it should. Concepts often have [b]invariants[/b]. [b]Invariants[/b] are... rules essentially that a class must follow. For the sake of example (don't do this in the real world) we wanted a class that was a square. While it has a width and a height, is has the [b]invariant[/b] that width and height always be equal. If you just supply width and height as public fields, someone could go in and make the width different from the height. Instead you would keep that storage private, and provide properties or methods that perform actions on the class while maintaining that class requirement. A more practical benefit is that the fewer things that can modify a field, the easier it is to then debug your program when the field ends up with the wrong value somehow.
[/quote]

Someone mind wording this so an idiot like myself can understand it, I have no idea what he's talking about, honestly.

Share this post


Link to post
Share on other sites
DarrenHorton    110
I hear what your saying. I don't understand 90% of what he said.

To tell you the truth I had to look up Encapsulation the other day. I had an idea but as it is used so often I needed a dictionaries definition.

I too struggle with some of the computer talk even though I'm an Englishman. The words aren't really in a persons everyday vocabulary.

Thanks to the poster for the attempt to explain some things.

Is there anyone who could provide an explanation that even a 13 year old could understand. LOL.

Share this post


Link to post
Share on other sites
BierbyteZ    115
[code]

class MyClass
{
//Attributes / Fields
private int myNumber;

//Properties
public int Number
{
get {return myNumber;}
set {myNumber = value;}
}

//Method
public void MyNumber(int p)
{
myNumber = p;
}
}

[/code]

[code]
MyClass c = new MyClass();

//Calling the Properties
//Set
c.Number = 1;

//Get
int gotNumber = c.Number;

//Calling the Method
c.MyNumber(5);

[/code]

[b]Class:[/b] Is a concept for modeling data. Classes are like blueprints for Objects which are created from a class.
Example Class Car can be used to create an Object Car.

[b]Attributes/Fields[/b]: Are the Attributes of the class and Objects. For example you can store the number of wheels of the car or the horsepower.

[b]Properties:[/b]Are a specific C# feature in other languages they are called Getter and Setter methods. The only purpose of this classes to access the Class attributes like number of wheels and horsepower. Why we need methods for it? because we declare attributes as private most of the time so you wont be able to change attrbiutes directly. Maybe you just want to return attribute values and dont change them.

[b]Methods:[/b]Offer specific calculations or algorithms like divide numbers or something.

The Reason why we Encapsulate the data is that we have a better overview about our program at the first place and that we will do less mistakes at programming. Its easier to use and you have better controls about your attributes and methods.

Share this post


Link to post
Share on other sites
BierbyteZ    115
[quote name='GraySnakeGenocide' timestamp='1307346330' post='4820007']
So Fields are class-specific variables, and Properties are the method-like feature to allow access to them outside of that class?
[/quote]

Yes

Because the attributes are private you have to acces them via methods/properties which are provided by the class itself

Share this post


Link to post
Share on other sites
caaraa    95
I try to make a few classes and have the bullets shooting from the ship but no joy.
[img]http://www.primeaffiliate.com/track/images/17.computers.jpg[/img][img]http://farm1.static.flickr.com/147/buddyicons/62288409@N00.jpg[/img]

Share this post


Link to post
Share on other sites
DarrenHorton    110
Thanks BierByteZ for the simplified explanation.

There is always. http://www.learnvisualstudio.net

For C# video Tutorials.

In the beginners video tutorials he shows how to do variables, properties

Classes such as Car/Engine etc

And stamp out new instances of car with car class defined properties

Perhaps also you might wanna look at the APP HUB'S tutorials

Here you can see objects such as player controlled ships and men, defined with parameters etc

The simplified collision detection programs are very easy. here's one. http://create.msdn.com/en-US/education/catalog/tutorial/collision_2d_rectangle

Share this post


Link to post
Share on other sites
Telastyn    3777
[quote name='GraySnakeGenocide' timestamp='1307346330' post='4820007']
So Fields are class-specific variables, and Properties are the method-like feature to allow access to them outside of that class?
[/quote]

No.

Fields may be private, protected, internal, protected internal, or public. If fields are public, then things outside of that class can access them. Fields are variables. They have a type and store some value in memory. Properties are... properties. They look like variables, and have a type, but do not store some value in memory (unless you're using auto-properties from C# 3.0). Properties have two parts, a getter and a setter. The getter is a method used whenever someone tries to access the property. Since there's no actual value stored in memory, you need to tell the program what the value should be. The setter is used whenever someone tries to write to (or assign something) to the property. Since there's no actual value stored in memory, you need to tell the program what to do with it.

If the original (or this) explanation wasn't clear... well crap. It's plain English, and I assumed you'd read at least a few chapters of a C# book. It might help if I understood more of your background or if we could focus on one specific question at a time.

Share this post


Link to post
Share on other sites
Serapth    6671
The terminology can be a bit confusing. You are close, but off by a bit.

In the simplest terms, think of "Fields" as the data of a class. The availability of a field to other classes has nothing to do with properties however, that instead is the roll of the modifiers.

A field is composed of at least one modifer, a type then a variable name, for example:

[code]public int myInteger;[/code]

The modifier in this case is [b]public[/b] which essentially means that other classes can access that data value. As telastyn said, other modifiers include [b]private[/b], [b]internal, protected [/b]& [b]protected internal. [/b] For now, lets just focus on public and private. Public means other classes can access, private means they don't have access. The other modifiers are mostly used when working with inheritance ( deriving other objects from your object ) and you can cross the bridge when you get to it. [b]static [/b] and [b]readonly [/b] also exist as modifiers, but lets just ignore that fact for now!


So, in summary, a field is a piece of data within a class and the fields modifier determines how that data can be accessed.


Now properties are super straight forward, just a bit oddly named. In just about every language, its pretty common to have private fields ( or member variables, choose your naming poison ) with public accessor functions. This means your data is [b]private [/b]to the class, but is accessed through a [b]public [/b]function.

Often it would look something like this:

[code]
class Demo
{
private int somePrivateInt; // field, not publicly accessible

public int GetSomePrivateInt()
{
return somePrivateInt;
}
}
[/code]

This kind of code became so common, C# provided a short cut version, the property, which looks like this:

[code]
class Demo
{
private int somePrivateInt;

public int SomePrivateInt
{
get { return somePrivateInt; }
set { somePrivateInt = value; }
}
}
[/code]

In this demo SomePrivateInt is a property that accesses somePrivateInt.

You may be thinking to yourself, why the hell would I want to do this? First off, it makes changing your class down the road much simpler, it adds one layer of abstraction between the other code consuming your code and your codes internal logic. For example, lets say you had a variable but somewhere down the road, you wanted it incremented every time you accessed it, its as simple as:


[code]
class Demo
{
private int somePrivateInt;

public int SomePrivateInt
{
get { return ++somePrivateInt; }
}
}
[/code]

Now, as you can see, the functionality of your class changed, but to any code calling Demo, it all seems exactly the same. Another thing to notice in the above code is, I removed the set {} code. This effectively makes somePrivateInt read only. You can choose to only implement set or get, and effectively make the accessed field read or write only.


Of course, properties don't have to be accessors for existing fields, they also can be computed values. Consider the following example:

[code]
class Rectangle
{
public int Width;
public int Height;

public int Area
{
get { return Width * Height; }
}
}
[/code]

In this case, the property is calculated on the fly.



Finally, you can use properties to defer initialization. Consider:

[code]
class Renderer
{
private SceneGraph mySceneGraph;

public SceneGraph MySceneGraph
{
get
{
if(mySceneGraph == null)
mySceneGraph = new SceneGraph();
return mySceneGraph;
}
}
}
[/code]

In this particular case, the allocation of mySceneGraph is deferred until the first time it is used. Note, the property doesnt HAVE to be the same name as what it accesses with the first letter capitalized, it's just a pretty standard naming convention.


Now, one very final example is the auto property. Back to our very first example:


[code]
class Demo
{
private int somePrivateInt;

public int SomePrivateInt
{
get { return somePrivateInt; }
set { somePrivateInt = value; }
}
}
[/code]

This kind of code is very very very common, so common in fact that C# 3 implemented a short hand version.


[code]
class Demo
{
public int SomePrivateInt
{
get;set;
}
}
[/code]

It has the exact same effect as the earlier demo, just a lot less typing.

Share this post


Link to post
Share on other sites
DarrenHorton    110
Wow thanks Serapth.

What a post. That was pretty clear and beginner friendly.

I've been re-reading my books and video tutorials today.

I went back to any earlier website and all the examples are beginner friendly, with programs to code calculators etc.

It's here. http://www.homeandlearn.co.uk/csharp/csharp.html

I think my biggest problem with learning is that I never wrote much code. It only really sinks in when you are problem solving.

At the moment it reminds me of learning trigonometry in advanced German.

I am or was a quick learner as I am holding a proffessional Licence in my last career, and got self-taught and qualified super quick.

But the bottom's fell out the job market, and who wants to work night shift anyway.

So hopefully I will be able to develop my C# skills quickly.

However Zero's and One's wizzing around memory and processors is not quite as tangible as Aircraft Engineering.

Thanks for the help.
[url="../../user/109204-serapth/"][/url]

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this