Search code examples
c#asp.net-mvcformsdatamodel

C# data model, are there any differences between using these form?


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?


Solution

  • 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