1

I'm going to build my MVC Web Application and I created my data models.
I found online many ways to compile a data model code. This is easiest one, using only public properties:

public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

But I also found a version using a private variable and a public properies, like this:

public class Person
{
    private int id;
    private string firstName;
    private string lastName;

    public int Id { get { return id; } set { id = value; } }
    public string FirstName { get { return firstName; } set { firstName = value; } }
    public string LastName { get { return lastName; } set { lastName = value; } }
}

What is the difference between these two data models? When is more advisable using the first one or the second one?

tereško
  • 56,151
  • 24
  • 92
  • 147
xnr_z
  • 992
  • 2
  • 14
  • 32

3 Answers3

4

This is the same like asking: what is a difference bwteen auto properties and normal properties.

Auto properties:

  • easy creation (less to type)
  • internal field is generated for you automatically by compiler
  • Not possible to debug (set a break point inside the property)

Normal properties

  • Sligtly more code to type
  • Easy to debug
  • More code can be injected inside get and set
Tigran
  • 59,345
  • 8
  • 77
  • 117
2

If first example compiler will create private field for every automatic property itself, but they behave exactly the same. More info on MSDN

I would suggest second approach as you have more control how property works, but there is nothing wrong in using first one.

gzaxx
  • 16,281
  • 2
  • 31
  • 53
0

The fiest block you have are auto-properties, and under the hood the c# will be compiled similar to the second block, so in this case there is no difference. Take a look at these posts here:

C# 3.0 auto-properties - useful or not?

What are Automatic Properties in C# and what is their purpose?

Any reason to use auto-implemented properties over manual implemented properties?

If you were implementing the INotifyPropertyChanged interface, then you would need to use the traditional way as you would be interacting with the property in the setter, see example...

http://msdn.microsoft.com/en-us/library/ms743695.aspx

Community
  • 1
  • 1
christiandev
  • 16,394
  • 8
  • 42
  • 74