Using fields vs. just defining a property?

I'm a little confused by something.

Let's say I have a simple class

public class Man { private string _name; //and a property Name public string Name { get { return _name; } set { if (value.Length > 15) Console.WriteLine("Error! Name length exceeds 15 characters!"); else _name = value; } 

Why should i use a field? Why not just define a property (Name) and use that everywhere? How will that break encapsulation?

If I rewrote the class like so (skipping the checks for length for now):

public class Man { public string Name {get; set;} } 

Why is this worse

I'm missing something basic here, I know.

by WhosListening via /r/csharp

Leave a Reply