Reputation: 8578
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;}
?
Upvotes: 1
Views: 549
Reputation: 1534
The difference you are looking for is called encapsulation.
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.
Upvotes: 1
Reputation: 28737
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
Upvotes: 2
Reputation: 168948
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.
Upvotes: 2