I don`t understand why and where we need to use properties and what is the real reason we need them.. Every article shows how to set and get values but none tell where exactly to use
Why are properties required in C#
Hi,
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.
Sandeep Singh ShekhawatPosted May 4, 2013, 3:04 AM
You can define entire logic in set block as well as get block.
You can validate value using properties accroding your logic which is defined in properties set block before fruther process same thing can do in get block to send value to user.
Suma MPosted May 6, 2013, 2:20 AM
Vithal WadjePosted May 4, 2013, 6:23 AM
Suma MPosted May 4, 2013, 2:20 AM
Is that the only purpose of properties ie to access private variables only?
Sandeep Singh ShekhawatPosted May 4, 2013, 1:56 AM
for example
public class Test
{
private int age = 0;
public int Age
{
set { age = value; }//assign user input value in age variable
get { return age; }//getting age variable value
}
}
And in another class we can access properies to assign and get values
public class Demo
{
Test objTest = new Test();
//assign value to property and variable
public void SetValue()
{
objTest.Age = 12;
}
//get value to property and variable
public void getValue()
{
System.Diagnostics.Debug.WriteLine(objTest.Age);
}
}
But I can do same thing with public variable so why use properties?
because we can add condition on input value in set block and can add addition on output value in get block
for example condition on input value
public class Test
{
private int age = 0;
public int Age
{
//assign user input value in age variable
set
{
if (value >= 18)
{
age = value;
}
else
{
age = 0;
}
}
get { return age; }//getting age variable value
}
}Pardeep MalikPosted May 4, 2013, 1:39 AM
Every class have some global variables, for the security purposes we have to declare them private, To get or set the value of global variable you have to need two method block,
first that sets the value of variable and second that return the value (get block), in c# property used instead of that block, actually property is a combination of get & set block,
Regards,
Pardeep Malik