Properties in C#  
Author Message
CJW99





PostPosted: Visual C# Language, Properties in C# Top

Hi all,

I've read about properties in C# and it is my uinderstanding that they are here to replace the 'setter' and 'getter' methods we all used have to manually create. BUT I cant create these for private variables. In the following:

class MyClass
{

private int x;
public int X
{
get
{
return x;
}
set
{
x = value;
}
}
}

Private int little x is 'getted' / 'setted' through public int big X. (e.g. MyClass.X = 10) If big X is public and little x is changed through big X, what is the point of having little x as private We could just have little X as public and remove big X totally out of the equation.

Thanks

Chris




Visual C#9  
 
 
aaronallport





PostPosted: Visual C# Language, Properties in C# Top

It is very bad OO practise to allow direct access to attributes, hence why get/set or properties are used. Having little x as a public attribute means that when x is manipulated within your class, it also affects anything using it.

 
 
boban.s





PostPosted: Visual C# Language, Properties in C# Top

Of course that you can have private properties. Properties have many purposes, not just to be interface to some private value. Sometime you want to have a property which will show some value or group of value in different format or type. Sometime you need to execute some code in property setter. So when you want to achive this, you use properties, and does some property is public or private is just a meter of accessibility and security.

 
 
Chatanya





PostPosted: Visual C# Language, Properties in C# Top

Hi Boban,

Thanks for your reply.

But I am intrested to know what is the use of private property as we have function to achieve same thing. In which case I really need private properties

Thanks and Regards,

ChatanYA Agrawal



 
 
CJW99





PostPosted: Visual C# Language, Properties in C# Top

Hmmm thanks Aaron, but my point here is that little x is practically public anyway considering that big X is also deemed public and we change little x through big X. If someone could supply a more accepted way of using properties to make getter and setter methods for a private variable it would be much appreciated.

Thanks again

Chris



 
 
Jeff Wharton





PostPosted: Visual C# Language, Properties in C# Top

What aaronallport said is correct as you are breaking OO convention. Besides, not all getters and setters are as simple as "return x" and "x = value". You may need to implement error handling or calculations based on the values being supplied or retuened.

For example:

class MyClass
{
private int x;
public int X
{
get
{
return DoComplexCalculation();
}
set
{
if (value < 0)
{
throw new ApplicationException("Invalid Value");
}
else
x = value;
}
}

private int DoComplexCalculation()
{
return x * 3 / 7 + 4;
}
}

If you made "int x" public, you would not be able to implement the above.



 
 
boban.s





PostPosted: Visual C# Language, Properties in C# Top

Properties are in fact methods for get and set accessors, and nothing more. I personaly preffer properties, but of course i don't use them always. I have more offen internal properties then private but maybe because i was in such situations. Small number of developers say that they don't need properties like in old days, but bigger part of them want them and want every way of extensibility around them like this having private properties, like having public getter and protected setter.

 
 
theblueeyz





PostPosted: Visual C# Language, Properties in C# Top

One place I like using private properties is when I have a variable that needs to be cast to a specific type every time I refer to it.

For example:

// I know for certain that myBrush is always a SolidBrush. But for extensibility purposes,
// I'll refer to it as 'Brush'.

private Brush myBrush;

// Now I create a private property that allows me to always access
// the brush as a SolidBrush, so that I don't have to dirty my code with tons of casts:
private SolidBrush MyBrush
{
get { return myBrush as SolidBrush; }
}

// Then in my code:
this.MyBrush.Color = whatever....

This is usually useful when I have a base class that I have several different objects deriving from. It allows me to put basic implementation in the base class, enough to simplify the child classes, without locking down the child classes to specific objects.


 
 
CJW99





PostPosted: Visual C# Language, Properties in C# Top

Aaaah cheers mate I think i'm understanding the concept more now.

Get and set are just some shortcut way.. and are incurring the extra overhead of an extra variable. No problem, thanks for your explanation.

Chris



 
 
Felan





PostPosted: Visual C# Language, Properties in C# Top

Actually it's not a shortcut way at all. If there is actually any extra overhead it is minimal and actually it is also quite possible that by using the getter/setter methods the compiler can do a better job of optimizing your code than if you make it a public member. More importantly it insulates your code against the need to change it and makes it easier to debug.

If you access a public member variable in 50 places in your code and something in your code does something bad to that variable but not always you will likely have a tough time finding it and an even tougher time fixing it. If you allow the class to be responsible for its data then you deal with the "something bad" in one spot by adjusting the code of the getter/setter to more appropriately handle the condition.

And really that's just the tip of the proverbial ice berg.


 
 
yazad_gandhi





PostPosted: Visual C# Language, Properties in C# Top

By using a Property you dont need to create two different methods to set a value and another to retrieve a value.

In a single property, with the same name you can get and set. Although this can also be achieved through an overloaded method.

You have a very good question as to Why use private properties.

Consider this:

private int Kilogms {

set {

grams= 1000*value;

kilogms = value;

}

get { return kilogms; }

}

private int Grams {

set {

grams= value;

kilogms = value / 1000;

}

get { return grams; }

}

If I want that each time I set Grams or Kilogms the other unit should also get the value, then i can use the above property. And if I dont want any other class to use them i make them private.

Again, this can also be done using overloaded methods, but a property would be simpler and can be used like:

Kilogms = 50;

this will set kilogrms = 50 and grams = 50000

I hope this was useful to you.

Regards



 
 
Figo Fei - MSFT





PostPosted: Visual C# Language, Properties in C# Top

Hi, Chatanya

Usually, we use properties to get some info about the class from outside, in this case we use public or protected.

Also, abstractly we can free modify properties as private, if we use them inside the class.

Thanks



 
 
James Curran





PostPosted: Visual C# Language, Properties in C# Top

Get and set are just some shortcut way.. and are incurring the extra overhead of an extra variable.

What extra overhead Property getters & setter work exactly like getter & setter methods you said you are familar with. They merely add a bit a syntactic sugar to make the source code a bit easier to read.



 
 
CJW99





PostPosted: Visual C# Language, Properties in C# Top

Hi James,

IThe overhead I meant was the declaration of the extra variable (big X). In this case we are getting and setting little x. If we were to write getter and setter methods manually there would be no need to have the variable big X.

Thanks

Chris



 
 
timvw





PostPosted: Visual C# Language, Properties in C# Top

Imho the advantage of properties is that they allow you to silently replace a class variable with a function...


 
 
boban.s





PostPosted: Visual C# Language, Properties in C# Top

First, i want to point that properties are just sintax, and when you build the assembly, properties are in reality get_"Name of property" and set_"Name of Property" methods. So you don't have to write methods, because the compiler do this for you.
Second, why properties. Well there are many reasons, maybe i cann't remember all, but here are some:
- Controlong type of access (Not all variable need read and write access, maybe just read from outside of the class),
- Controling the value that is writed in property, like type, range, business logic, ....
- Change the value in different format for outside,
- Create one property that will be join of two or more private variables
- Create more than one property representing one private value, but in different format
- Activate other actions when one property is changed, like raising events, changing something else in applications, calling some methods, ....

Properties should be used always and it should be general rule. Having public variable should be avoided. Having properties doesn't neccessary means that are for outside access. Sometime you will use the power of properties also for internal class usage. This means that properties can be private also.



 
 
Jim Tomasko





PostPosted: Visual C# Language, Properties in C# Top

You are allowed to have private properties. Typically, for my own private members I do not write properties, but there's no really good reason not to that I can think of.

After all, we make public properties to hide the details, so that if we want to do any bounds checking, filtering or such we can provide it in the property in one place, which greatly aids with code maintenance. (In fact, I would go so far as to say that NONE of our member variables should ever be public, and that we should ALWAYS use properties for them... but that's a question we all have to deal with on our own.)

The very first "Item" in the book "Effective C#" claims we should always use properties for a variety of reaons. I'll give just one here:

Quote from the book: Because properties are implemented with methods, adding multi-threaded support is easier. Simply enhance the implementation of the get and set methods to provide synchronized access to the data:

public string Name

{

get { lock (this) { return _name; } }

set { lock (this) { _name = value; } }

}

So will i start making private members properties Probably not today as a rule, but I might be sorry some day. Bill Wagner's book has a lot more reasons why we should always use properites.