If both get and set are compulsory in C# automatic properties, why do I have to bother specifying ‘get; set;’ at all?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
ERROR: A property or indexer may not be passed as an out or ref parameter
If you didn’t specify
{get; set;}then the compiler wouldn’t know if it’s a field or a property. This is important becasue while they ‘look’ identical the compiler treats them differently. e.g. Calling ‘InitAnInt’ on the property raises an error.You shouldn’t create public fields/Variables on classes, you never know when you’ll want to change it to have get & set accessors, and then you don’t know what code you’re going to break, especially if you have clients that program against your API.
Also you can have different access modifiers for the get & set, e.g. {get; private set;} makes the get public and the the set private to the declaring class.