Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Public Properties and Private Members C#

What are the benefits of only using public properties instead of using the public property to access a private variable?

For example

public int iMyInt { get; set; }

instead of

private int myint;
public int iMyInt { get { return myint; } set { myint = value; } }

Other than letting .NET manage the variable / memory underneath the property, what are the advantages (or disadvantages for that matter)?

like image 310
CodeMonkey1313 Avatar asked Nov 30 '25 12:11

CodeMonkey1313


1 Answers

Using automatic properties (the first example) requires less typing.

It is highly recommended to have only public properties and not public fields. Many properties are simple wrappers around private fields. Automatic properties save you the time and hassle of manually creating the property and backing field.

The actual code behind automatic and manual properties for the simple case you mentioned should be nearly identical.

like image 162
Michael Avatar answered Dec 02 '25 02:12

Michael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!