Could someone explain something I don't quite 'get' about OOP?

Associate
Joined
28 Jun 2005
Posts
2,174
Location
Behind you
Hi experts,

I'm learning OOP using C# and I get the basic concepts of OOP. There is one thing I don't get though when defining a class:-

clas MyClass
Private Int _MyVar

Public Int MyVar


Can someone explain the point of private properties when there is a public version in the same class?

Thanks
 
It depends if the property is a part of your class/object interface. (I don't mean "interface MyInterface {}" I mean the literal term.)

They are also different, take note of the underscore.

When designing a class/object, unless I specifically want the property to be available outside of the object, I will assign it private, protected if it's abstract and access is required by the child class.
 
Code:
private SQLConnection dbconn;

public SQLConnection DbConn {
	get {
		if (dbconn == null) { dbconn = DbConnCreator(); }
		return dbconn;
	}
}

Normally it's used in the above case where you have a public property. Everyone else gets at the sqlconnection instance by calling the property. The actual instance is stored in the private property, and the public property does some logic to make sure it returns a valid sqlconnection.

You could just make the private property public, but then you'd have to move the checking logic into every class that requested a sqlconnection which is bad, and difficult to manage. Remember, a lot of things are the way they are in OOP because there's very rarely a piece of software that is never updated. Any major code that is written will probably be changed/adjusted/rewritten in the future to improve performance, add functionality etc. It's much much easier to work on properly written OOP applications.
 
Last edited:
Back
Top Bottom