get (C# Reference)
The get
keyword defines an accessor method in a property or indexer that returns the property value or the indexer element. For more information, see Properties, Auto-Implemented Properties and Indexers.
The following example defines both a get
and a set
accessor for a property named Seconds
. It uses a private field named _seconds
to back the property value.
class TimePeriod
{
private double _seconds;
public double Seconds
{
get { return _seconds; }
set { _seconds = value; }
}
}
Often, the get
accessor consists of a single statement that returns a value, as it did in the previous example. You can implement the get
accessor as an expression-bodied member. The following example implements both the get
and the set
accessor as expression-bodied members.
class TimePeriod
{
private double _seconds;
public double Seconds
{
get => _seconds;
set => _seconds = value;
}
}
For simple cases in which a property's get
and set
accessors perform no other operation than setting or retrieving a value in a private backing field, you can take advantage of the C# compiler's support for auto-implemented properties. The following example implements Hours
as an auto-implemented property.
class TimePeriod2
{
public double Hours { get; set; }
}
C# Language Specification
For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage.
See also
Feedback
https://aka.ms/ContentUserFeedback.
Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see:Submit and view feedback for