Isn't it better to make a field public than providing its property with both set { } and get { } block? After all the property will allow the user to both read and modify the field so why not use public field instead? Motivate your answer


Not always! Properties are not just to provide access to the fields; rather, they are supposed to provide controlled access to the fields of our class. As the state of the class depends upon the values of its fields, using properties we can assure that no invalid (or unacceptable) value is assigned to the fields.

Eg:

private int age;

public int Age

{

get

{

return age;

}

set

{

if(value <> 100)

//throw exception

else

age = value;

}

}



No comments:

Post a Comment