0

I have this

public int CityId { get; set; }

and

public int CityId;

If I use first - it works in EF code first while the second - doesn't. But if I definte {get; set;} and do nothing else, what is the exact difference between a simple definition? I understand that I can add some additional/customized code to {get; set;} layout, but doesn't it work exactly the same if without {get; set;}?

Andrius Naruševičius
  • 8,348
  • 7
  • 49
  • 78
  • 1
    The latter is a field, the former is a property. – vcsjones Apr 26 '13 at 20:20
  • Long term, properties provide additional benefits (like the ability to declare as `virtual`, `abstract`, or in interfaces). Sometimes significantly, even though the calling/usage code may be identical (assigning/getting values to/from _look_ like the same C# syntax), it is a breaking change to switch. Third-parties leveraging your code _must_ recompile their code to match the change. If they simply replace the compiled DLLs without recompiling, they will receive runtime errors. – Chris Sinclair Apr 26 '13 at 20:37
  • I can't speak for EF, but my past experience with NHibernate _required_ the members to be properties (maybe even virtual? Maybe just for lazily-loading bags/collections) because it would compile _subclasses_ on-the-fly which would override/implement the property behaviour to lazily load data from the database. Such behaviour is (likely) _impossible_ with fields. – Chris Sinclair Apr 26 '13 at 20:40

3 Answers3

2

With this syntax:

public int CityId { get; set; }

you're actually creating an auto-implemented property and behind the scenes it gets translated to this:

private int _CityId;
public int CityId { 
    get
    {
        return _CityId;
    } 
    set
    {
        _CityId = value;
    }
}

This syntax:

public int CityId;

is just a field

cdhowie
  • 158,093
  • 24
  • 286
  • 300
Kenneth
  • 28,294
  • 6
  • 61
  • 84
2
public int CityId;

This is a field.

public int CityId { get; set; }

This is a property, and the compiler will generate a private field for you automatically to back the property.

They are two different things. A property provides a getter, a setter, or both. The "get" and "set" operations on properties are compiled as method calls.

A field is just an exposed variable. It is generally considered bad practice for fields to be public.

cdhowie
  • 158,093
  • 24
  • 286
  • 300
1

The difference you are looking for is called encapsulation.

example

In your example is not a big difference between the field and the property. The field got a better performance than the property because it doesn't need to call a method to access it. Anyway the disadvantages of a field is that everyone can access it and you (the class holding the field) don't have any control about it.

WhileTrueSleep
  • 1,524
  • 1
  • 19
  • 32