Properties
Why does properties use in class instead of normal variable?
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Upendra Pratap ShahiPosted Jun 29, 2015, 1:08 AM
What is the difference between variable and property?
When we talk about any class or object it has two things – Data and Business logic. When it comes to data we have variables. When it comes to Business logic we have some intermediate results and for that again we have variables.
Variables are simply named memory locations where we can store our data or temporary results.
Let’s have a small example about variable.
public class Customer
{
}
.
.
Customer c=new Customer();
c.customerName= “Sukesh Marla”;
public class Customer
{
publicint age;
}
.
.
Customer c=new Customer();
c.customerName= “Sukesh Marla”;
c.age=55; //Perfect
c.age=555; // Ohh!! No, what the hell is this?
c.age= -5; //What rubbish.
Our data is not protected. It should be validated before it dumped into variable.
Now the question is who will do the validation?
We have two developers with us now – one who have developed the above class (let’s call him creator) and second who will use this class (let’s call him end developer).
If end developer do this validation then,
So the final decision is to put validation in Customer class itself by its creator.
For this we will simply create a function in Customer class which will do the validation and return either true or false. End developer will just call that function before assigning value.
Example
public class Customer
{
publicint age;
publicboolIsValidAge(int _age)
{
{
returntrue;
}
else
}
}
.
.
c.customerName=”Sukesh Marla”;
intTempAge=int.parse(TxtAge.Text);
if(c.IsValidAge(TempAge))
{
}
Is there any issue more?
Yes, what if end developer fail to forget to call IsValidAge method before assigning value.
Ultimate solution – Property
Our data should get validated as soon as someone try to put values to it and for that we have properties in C#. It is an encapsulation over our normal variables providing get and set accessory. Get will be executed when someone try to retrieve the value of it and set will be executed when someone try to modify the value of it. Thus it makes our data protected.
Example :
public class Customer
{
privateint _age;
publicint Age
{
get
{
}
If(_age>0 && _age<100)
{
_age=Value;
}
else
}
.
.
c.customerName=”Sukesh Marla”;
intTempAge=int.parse(TxtAge.Text);
if(c.IsValidAge(TempAge))
{
}
Sujeet SumanPosted Jun 28, 2015, 11:41 PM
Pankaj Kumar ChoudharyPosted Jun 28, 2015, 7:53 PM
SharadPosted Jun 28, 2015, 1:57 PM
People is getting in to sectionOne pretty easily, there wasn't any checking.
Now see with implementing properties:
now you checked the person and know about whether he has something evil with him.