Possible Duplicate:
What is the difference between a field and a property in C#
I don't understand the difference between field and properties in a class.
Possible Duplicate:
What is the difference between a field and a property in C#
I don't understand the difference between field and properties in a class.
A field is a storage location for information. For example, if the field is of type int
, it stores a 32-bit integer (a number from around minus 4 billion to around plus 4 billion).
A property is almost like a method or a pair of methods. It’s just code. No storage. For example, instead of
public int FortySeven
{
get
{
return 47;
}
}
you could also write
public int GetFortySeven()
{
return 47;
}
and it would be more or less the same thing; the only difference is that you write FortySeven
(no parentheses) but GetFortySeven()
(with parentheses).
Of course, properties can also have a setter, which means that
public int FortySeven
{
set
{
Console.WriteLine(value);
}
}
is pretty much the same thing as
public void SetFortySeven(int value)
{
Console.WriteLine(value);
}
and now instead of FortySeven = 47
you write SetFortySeven(47)
, but otherwise it is functionally the same.
An automatically-implemented property looks like this:
public int MyProperty { get; set; }
This code declares both a field and a property, but the field is invisible and you can only access the property. It uses the invisible field for its storage.