Need help understanding Encapsulation, Properties and Fields in C#

Started by
12 comments, last by DarrenHorton 12 years, 10 months ago
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
Advertisement

So Fields are class-specific variables, and Properties are the method-like feature to allow access to them outside of that class?


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.
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:

public int myInteger;

The modifier in this case is public which essentially means that other classes can access that data value. As telastyn said, other modifiers include private, internal, protected & protected internal. 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. static and readonly 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 private to the class, but is accessed through a public function.

Often it would look something like this:


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

public int GetSomePrivateInt()
{
return somePrivateInt;
}
}


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


class Demo
{
private int somePrivateInt;

public int SomePrivateInt
{
get { return somePrivateInt; }
set { somePrivateInt = value; }
}
}


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:



class Demo
{
private int somePrivateInt;

public int SomePrivateInt
{
get { return ++somePrivateInt; }
}
}


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:


class Rectangle
{
public int Width;
public int Height;

public int Area
{
get { return Width * Height; }
}
}


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



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


class Renderer
{
private SceneGraph mySceneGraph;

public SceneGraph MySceneGraph
{
get
{
if(mySceneGraph == null)
mySceneGraph = new SceneGraph();
return mySceneGraph;
}
}
}


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:



class Demo
{
private int somePrivateInt;

public int SomePrivateInt
{
get { return somePrivateInt; }
set { somePrivateInt = value; }
}
}


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



class Demo
{
public int SomePrivateInt
{
get;set;
}
}


It has the exact same effect as the earlier demo, just a lot less typing.
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]

This topic is closed to new replies.

Advertisement