Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use get and set in C# class declaration [duplicate]

Tags:

c#

Possible Duplicate:
Difference between Property and Field in C# .NET 3.5+

What's the difference between using

public string Username { get; set; }

and using

public string Username;

I have always been using the first one, but wanted to understand if there is any difference between the two, and scenarios when one should prefer over the other.

like image 411
Yasser Shaikh Avatar asked Jan 20 '26 11:01

Yasser Shaikh


1 Answers

public string Username { get; set; }
  • is a Property.

while

public string Username;
  • is a Public variable.

For more comparison,

  • Reflection works differently on variables vs. properties, so if you rely on reflection, it's easier to use all properties.
  • You can't databind against a variable.
  • Changing a variable to a property is a breaking change.

Other link

  • Properties vs. Public Variables
like image 123
John Woo Avatar answered Jan 23 '26 01:01

John Woo