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.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Sandeep Singh ShekhawatRank #147 · 15.6K reputationPosted May 3, 2013, 11:04 PM EDT
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.
Pardeep Malik129 reputationPosted May 3, 2013, 9:39 PM EDT
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
Sandeep Singh ShekhawatRank #147 · 15.6K reputationPosted May 3, 2013, 9:56 PM EDT
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
}
}Suma M161 reputationPosted May 3, 2013, 10:20 PM EDT
Is that the only purpose of properties ie to access private variables only?
Vithal WadjeRank #19 · 47.2K reputationPosted May 4, 2013, 2:23 AM EDT
Suma M161 reputationPosted May 5, 2013, 10:20 PM EDT