C# Expression-Bodied Members

C# 6.0 sürümü ile birlikte metotlar ve read only özellikler için Expression-Bodied Members tanımını tanıttı ve sürüm 7’de bunu property, constructor, finalizer ve index oluşturucuları içerecek şekilde genişletti.

Expression-Bodied Member Syntax (Sözdizimi)

member => expression;
  • member bir metot, property, constructor, finalizer ve index oluşturucusu olabilir.
  • Expression (İfade), herhangi bir geçerli ifadedir.

Metot

Bir metodun, türü metodun dönüş türüyle eşleşen bir değer döndüren tek bir ifadesi varsa, bir Expression-Bodied Members tanımı kullanabilirsiniz.

class Person
{
    public string FirstName { get; set; }
    
    public string LastName { get; set; }   

    public byte Age { get; set; }

    public string GetFullName()
    {
        return $"{FirstName} {LastName}";
    }
}

Bu Person sınıfında GetFullName() metodu, metodun dönüş tipiyle eşleşen bir string döndürür:

public string GetFullName()
{
    return $"{FirstName} {LastName}";
}

Bu nedenle, Expression-Bodied Members’ı metotda aşağıdaki gibi kullanabilirsiniz:

class Person
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public byte Age { get; set; }

    public string GetFullName() => $"{FirstName} {LastName}";
 
}

Read-only Property

C# 6’dan başlayarak, read-only bir özellik için Expression-Bodied Members tanımını kullanabilirsiniz. Örneğin, CanVote read-only özelliğini Person sınıfına ekleyelim.

class Person
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public byte Age { get; set; }

    public bool CanVote
    {
        get
        {
            return Age >= 16 && Age <= 65;
        }
    }

    public string GetFullName() => $"{FirstName} {LastName}";
}

CanVote özelliği read-only olduğundan, şuna benzer bir Expression-Bodied Members tanımı kullanabilirsiniz:

class Person
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public byte Age { get; set; }

    public bool CanVote => Age >= 16 && Age <= 65;

    public string GetFullName() => $"{FirstName} {LastName}";
  
}

Constructors

Aşağıdaki örnek, constructor’da skill adını Name özelliğine atayan bir expression’a sahip Skill sınıfını tanımlar:

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

    public Skill(string name)
    {
        Name = name;
    }
}

Bu nedenle, Skill constructor için Expression-Bodied Members tanımını aşağıdaki gibi kullanabilirsiniz:

class Skill
{
    public string Name { get; set; }
    public Skill(string name) => Name = name;
}