-4

What is the difference between a variable define in the class with or without {get; set;}. For example if I declare a variable like this

public string VariableName { get; set; }

and

public string VariableName;

What is the difference and if there is no difference than why and when to use get set?

Mohit Shrivastava
  • 12,996
  • 5
  • 31
  • 61
  • 2
    `{get; set;}` makes it an automatic property. Read about fields and properties to get better understanding of the difference. – MarcinJuraszek Feb 18 '15 at 01:39
  • @MarcinJuraszek the "duplicate" question actually does not reveal the *difference* between them. From this question perspective the "duplicate" is not helpful at all. – zerkms Feb 18 '15 at 01:41
  • I do not agree with the Duplicate mark. The question that this one refers to explains the difference between a field and a property, which is only part of the question. OP is also asking why one would prefer an automatic property with no access modifier changes per accessor over a simple field. – Bas Feb 18 '15 at 01:44
  • Related http://stackoverflow.com/questions/653536/difference-between-property-and-field-in-c-sharp-3-0 – Brian Rasmussen Feb 18 '15 at 01:46
  • I think I am not able to make myself clear in the question. but the links provided are not helpful in my question context but definitely are good. – Mohit Shrivastava Feb 18 '15 at 01:49
  • 1
    @Anthony Pegram Why did you mark this as a duplicate of an answer that is marked as a duplicate? – Rufus L Feb 18 '15 at 02:17
  • @RufusL, despite it being closed, I thought it had fitting answers from knowledgeable contributors. If you disagree on the applicability, vote to reopen. – Anthony Pegram Feb 18 '15 at 02:43

1 Answers1

1

On the calling side, properties and fields generate different code. Fields are accessed directly, but properties call a function in the class to both get and set the value. If your class is in a separate DLL from the caller, and you later want to change it to a property because you no longer store the actual value, but can still derive it from other data, or you want to trigger other changes or notification when it is set, or you want to provide some kind of locking around the retrieval or changing of the valid, or any number of other reasons, you will have to recompile the calling DLL in order for it to work. If you use a property, you can change the implementation of the getter and/or setter and the calling code will work without recompiling.

James
  • 2,730
  • 1
  • 20
  • 33