Jump to content

  • Log In with Google      Sign In   
  • Create Account

We're offering banner ads on our site from just $5!

1. Details HERE. 2. GDNet+ Subscriptions HERE. 3. Ad upload HERE.


Need help understanding Encapsulation, Properties and Fields in C#


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
13 replies to this topic

#1 Bill Fountaine   Members   -  Reputation: 193

Like
0Likes
Like

Posted 05 June 2011 - 09:52 AM

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.

Sponsor:

#2 Telastyn   Crossbones+   -  Reputation: 3730

Like
0Likes
Like

Posted 05 June 2011 - 10:15 AM

Classes represent a cohesive concept. Concepts have data that represent their state or configuration, and methods that perform some action or change the state/configuration.

Fields represent that state or configuration that is required by your class to do... whatever it's doing.
Properties behave like fields, but (unless they're auto properties) don't actually store anything. 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 store the area of the rectangle. You can store the width and height, and then provide Area as a property, 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 invariants. Invariants 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 invariant 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.

#3 blackbook   Members   -  Reputation: 110

Like
0Likes
Like

Posted 05 June 2011 - 12:38 PM

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. http://www.csharp-station.com/default.aspx

#4 Serapth   Crossbones+   -  Reputation: 5703

Like
0Likes
Like

Posted 05 June 2011 - 01:05 PM

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!



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.




#5 Bill Fountaine   Members   -  Reputation: 193

Like
1Likes
Like

Posted 05 June 2011 - 09:07 PM

Classes represent a cohesive concept. Concepts have data that represent their state or configuration, and methods that perform some action or change the state/configuration.

Fields represent that state or configuration that is required by your class to do... whatever it's doing.
Properties behave like fields, but (unless they're auto properties) don't actually store anything. 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 store the area of the rectangle. You can store the width and height, and then provide Area as a property, 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 invariants. Invariants 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 invariant 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.


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

#6 blackbook   Members   -  Reputation: 110

Like
0Likes
Like

Posted 06 June 2011 - 12:43 AM

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.

#7 BierbyteZ   Members   -  Reputation: 115

Like
2Likes
Like

Posted 06 June 2011 - 01:23 AM


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


MyClass c = new MyClass();

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

//Get
int gotNumber = c.Number;

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


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

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

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

Methods: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.
Java / C# Developer

#8 Bill Fountaine   Members   -  Reputation: 193

Like
0Likes
Like

Posted 06 June 2011 - 01:45 AM

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

#9 BierbyteZ   Members   -  Reputation: 115

Like
0Likes
Like

Posted 06 June 2011 - 01:58 AM

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


Yes

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

#10 caaraa   Members   -  Reputation: 95

Like
0Likes
Like

Posted 06 June 2011 - 02:06 AM

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

#11 blackbook   Members   -  Reputation: 110

Like
0Likes
Like

Posted 06 June 2011 - 03:10 AM

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

#12 Telastyn   Crossbones+   -  Reputation: 3730

Like
0Likes
Like

Posted 06 June 2011 - 08:11 AM

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.

#13 Serapth   Crossbones+   -  Reputation: 5703

Like
1Likes
Like

Posted 06 June 2011 - 09:28 AM

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.

#14 blackbook   Members   -  Reputation: 110

Like
0Likes
Like

Posted 06 June 2011 - 12:34 PM

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.





Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS