EUNJIHA / Dev

✍🏻개념 정리
1 stars 0 forks source link

[C#] Member(Fields, Properties, Methods) #2

Open EUNJIHA opened 4 years ago

EUNJIHA commented 4 years ago

✏Fields

A field is a variable of any type that is declared directly in a class or struct.

✏Methods

A method is a code block that contains a series of statements.

✏Properties (형식: Fields, 내용: Methods)

A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field.

참고 - Properties (C# Programming Guide)

1. Properties with backing fields

class TimePeriod
{
   private double _seconds;

   public double Hours
   {
       get { return _seconds / 3600; }
       set { 
          if (value < 0 || value > 24)
             throw new ArgumentOutOfRangeException(
                   $"{nameof(value)} must be between 0 and 24.");

          _seconds = value * 3600; 
       }
   }
}

2. Expression body definitions

public class Person
{
   private string _firstName;
   private string _lastName;

   public Person(string first, string last)
   {
      _firstName = first;
      _lastName = last;
   }

   public string Name => $"{_firstName} {_lastName}";   
}

3. Auto-implemented properties

public class SaleItem
{
   public string Name 
   { get; set; }

   public decimal Price
   { get; set; }
}