Auto Property etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
Auto Property etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

2 Eylül 2018 Pazar

Auto Property

Auto Property
Property kelimesi C# dilinde başka bir anlam kazanmış, biraz scripting dillerindeki Property ile karıştırılmaya müsait bir kelime. Normalde Java ve C#'ta sınıf alanlarına "Field" denilir. C++'ta ise "member variable" denilir.

Bir Field'ın compiler tarafından yaratılması, get ve set metodlarının otomatik oluşturulmasını istiyorsak Auto Property kullanırız.

Auto Property ile Serialization
Property'ler serialize edilirler.

Auto Property ile Modifier
Getter ve Setter modifier alabiliyor. Şöyle yaparız:
public string foo { get; private set; }
AutoProperty ve Kalıtım
Ata sınıfta Auto Property virtual modifier kelimesi ile tanımlanır. Şöyle yaparız.
public class MyBase {
  public virtual String A {
    get {
      return "getBaseA";
    }
    set {
      throw new NotSupportedException("setBaseA");
    }
  }
}
Alt sınıfta Auto Property override modifier kelimesi ile tanımlanır. Şöyle yaparız.
public class MyDerivedA: MyBase {
  public override String A {
    get {
      return "s";
    }
    set { // set is overridden, now set does nothing
    }
  }
}
Get ve Set metodlarından istediğimizi override ederiz. Eğer Set'i override etmek istemiyorsak şöyle yaparız.
public class MyDerivedB: MyBase {
  public override String A {
    get {
      return "s";
    }
    // set is not overridden, same as in the base class
  }
}
Bu durumda şu davranışı elde ederiz.
// Does nothing: overridden MyDerivedA.A.set is called
MyBase test1 = new MyDerivedA();
test1.A = "Sample";

// Will throw NotSupportedException (base MyBase.A.set is called)
MyBase test2 = new MyDerivedB();
test2.A = "Sample";
Auto Property Initializer
Açıklaması şöyle.
C# 6 enables you to assign an initial value for the storage used by an auto-property in the auto-property declaration:
Şöyle yaparız.
public class CustomerResult
{
  public string CompanyStatus { get; set; }
  public OverallResult Result { get; set; } = new OverallResult();
}
Auto Property Initializer For Read Only Fields
Auto Property Initializer For Read Only Fields yazısına taşıdım

Ne Zaman Public Metod Tercih Edilmeli
Bir property her bir zaman değer dönmelidir. Hesaplanan değerlerin property yerine public metod yapılması tavsiye ediliyor.

Auto Property ile Inline Kod
Property'ler inline edilebilirler ancak ben böyle iyileştirmeleri ömrüm boyunca sevmedim.
private SqlMetaData[] meta;

[MethodImpl(MethodImplOptions.AggressiveInlining)]
private SqlMetaData[] Meta
{
  get
  {
    return this.meta;
  }
}
Auto Property Ref Parametre Olarak Kullanılamaz
MSDN şöyle diyor
You can't use the ref and out keywords for the following kinds of methods:
  • Async methods, which you define by using the async modifier.
  • Iterator methods, which include a yield return or yield break statement.
  • Properties are not variables. They are methods, and cannot be passed to ref parameters.






28 Eylül 2017 Perşembe

Auto Property Initializer For Read Only Fields

Giriş
Auto Property Initializer For Read Only Fields C# 6.0 ile gelen bir özellik. Sadece getter metodu var.

Bu özelliğin iki farklı alt çeşidi var. İlki constructor içinde atanan değer, ikincisi ise çağrılma anında atanan değer yani "expression bodied property".

Birinci çeşit property = ... şeklinde kodlanır
İkinci çeşit property => ... şeklinde kodlanır

1. Constructor içinde atanan değer (auto property initialization)
Bu yöntemde nesne içind readonly (backing field) bir değişken yaratılır.

Örnek
Şöyle yaparız. Burada alana nesnenin yaratılma anında bir kere değer atanır.
public DateTime DogCreationTime { get; } = DateTime.Now;

Örnek
Şöyle yaparız.
public string Name { get; } = "bob";
Bu kod aslında şununla aynıdır.
private readonly string _name = "bob";

public string Name
{
  get
  {
    return _name ;
  }
}
Örnek
Şöyle yaparız.
public List<String> Names { get; } = new List<String>() {"bob"};
Bu kod aslında şununla aynıdır.
private readonly List<string> _names = new List<string>() {"bob"};

public string Names 
{
  get
  {
    return _names;
  }
}
Örnek
Bu sefer constructor içinde bir değer atamak istersek alanı tanımlamak için şöyle yaparız.
public int Foo { get; } 
Constructor içinde şöyle yaparız.
public MyClass()
{
  Foo = 5;
}

2. Çağrılma anında atanan değer (expression bodied property)

Örnek
Şöyle yaparız. Sabit bir sayı döndüğümüz için constructor içinde atanan değer ile aynı şeydir.
public int Foo => 5;
Bu örnekte Foo alanı için backing field üretilmez. Kod şöyledir.
public int Foo { get { return 5; } }
Örnek
Şöyle yaparız.
public string Name => "bob";
Üretilen kod şöyledir.
public string Name
{
  get
  {
    return "bob";
  }
}
Örnek 
Şöyle yaparız
public List<String> Names => new List<String>() {"bob"};
Üretilen kod şöyledir. He rseferinde yeni liste döner.
public List<string> Names
{
  get
  {
    return new List<string>() {"bob"};
  }
}
3. Farkı Görmek 
constructor içinde atanan değer ve çağrılma anında atanan değer arasındaki farkı görmek için şöyle yaparız. Start alanı constructor içinde atanır. Now alanı ise çağrılma anında atanır
class SomeTestClass
{
  public DateTime Start { get; } = DateTime.Now;

  public DateTime Now => DateTime.Now;
}