Skip to content

Extension Methods

Genel Bakış

Extension Methods (Genişletme Metodları), mevcut tiplere yeni metodlar eklememizi sağlayan bir C# özelliğidir. Bu metodlar, orijinal tipin kaynak koduna erişmeden veya türetme yapmadan, tipin işlevselliğini genişletmemize olanak tanır.

Extension Method Tanımlama

  1. Temel Extension Method

    public static class StringExtensions
    {
        public static bool IsNullOrEmpty(this string str)
        {
            return string.IsNullOrEmpty(str);
        }
    }
    
    // Kullanımı
    string text = "Merhaba";
    bool isEmpty = text.IsNullOrEmpty();
    

  2. Generic Extension Method

    public static class CollectionExtensions
    {
        public static bool IsNullOrEmpty<T>(this IEnumerable<T> collection)
        {
            return collection == null || !collection.Any();
        }
    }
    
    // Kullanımı
    List<int> numbers = new List<int>();
    bool isEmpty = numbers.IsNullOrEmpty();
    

  3. Parametreli Extension Method

    public static class StringExtensions
    {
        public static string Repeat(this string str, int count)
        {
            return string.Concat(Enumerable.Repeat(str, count));
        }
    }
    
    // Kullanımı
    string result = "Merhaba".Repeat(3); // "MerhabaMerhabaMerhaba"
    

Extension Method Kullanım Alanları

  1. String İşlemleri

    public static class StringExtensions
    {
        public static string ToTitleCase(this string str)
        {
            return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str.ToLower());
        }
    
        public static bool IsValidEmail(this string email)
        {
            return Regex.IsMatch(email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$");
        }
    }
    

  2. Koleksiyon İşlemleri

    public static class CollectionExtensions
    {
        public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source)
        {
            return source.OrderBy(x => Guid.NewGuid());
        }
    
        public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> source, Func<T, TKey> keySelector)
        {
            return source.GroupBy(keySelector).Select(x => x.First());
        }
    }
    

  3. DateTime İşlemleri

    public static class DateTimeExtensions
    {
        public static bool IsWeekend(this DateTime date)
        {
            return date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek == DayOfWeek.Sunday;
        }
    
        public static int GetAge(this DateTime birthDate)
        {
            var today = DateTime.Today;
            var age = today.Year - birthDate.Year;
            if (birthDate.Date > today.AddYears(-age)) age--;
            return age;
        }
    }
    

Extension Method Best Practices

  1. Namespace Kullanımı

    namespace MyApp.Extensions
    {
        public static class StringExtensions
        {
            // Extension methods
        }
    }
    

  2. Statik Sınıf Kullanımı

    public static class Extensions
    {
        // Tüm extension methods burada
    }
    

  3. Method İsimlendirme

    public static class StringExtensions
    {
        // Açıklayıcı isimler kullan
        public static string RemoveWhitespace(this string str)
        {
            return new string(str.Where(c => !char.IsWhiteSpace(c)).ToArray());
        }
    }
    

Extension Method ve Interface'ler

  1. Interface Extension

    public interface ILogger
    {
        void Log(string message);
    }
    
    public static class LoggerExtensions
    {
        public static void LogError(this ILogger logger, Exception ex)
        {
            logger.Log($"Hata: {ex.Message}");
        }
    }
    

  2. Generic Interface Extension

    public interface IRepository<T>
    {
        T GetById(int id);
    }
    
    public static class RepositoryExtensions
    {
        public static IEnumerable<T> GetByIds<T>(this IRepository<T> repository, IEnumerable<int> ids)
        {
            return ids.Select(id => repository.GetById(id));
        }
    }
    

Mülakat Soruları

  1. Extension Method Temelleri
  2. Extension method nedir ve ne işe yarar?
  3. Extension method'lar nasıl tanımlanır?
  4. Extension method'ların avantajları ve dezavantajları nelerdir?

  5. Extension Method Kullanımı

  6. Extension method'lar ne zaman kullanılmalıdır?
  7. Extension method'lar ve normal method'lar arasındaki farklar nelerdir?
  8. Extension method'ların performans etkisi nedir?

  9. Extension Method ve OOP

  10. Extension method'lar OOP prensiplerini nasıl etkiler?
  11. Extension method'lar inheritance'a alternatif midir?
  12. Extension method'lar encapsulation'ı nasıl etkiler?

  13. Extension Method ve Interface'ler

  14. Interface'lere extension method eklemek ne zaman uygundur?
  15. Interface extension'ların kullanım alanları nelerdir?
  16. Interface extension'ların sınırlamaları nelerdir?

  17. Extension Method ve Generic'ler

  18. Generic extension method'lar nasıl tanımlanır?
  19. Generic extension method'ların kullanım alanları nelerdir?
  20. Generic extension method'larda type constraint'ler nasıl kullanılır?

  21. Extension Method ve LINQ

  22. LINQ extension method'ları nasıl çalışır?
  23. Custom LINQ extension method'ları nasıl yazılır?
  24. LINQ extension method'larında deferred execution nasıl sağlanır?

  25. Extension Method ve Testing

  26. Extension method'lar nasıl test edilir?
  27. Extension method testlerinde dikkat edilmesi gerekenler nelerdir?
  28. Extension method'lar unit test'leri nasıl etkiler?

  29. Extension Method ve Performans

  30. Extension method'ların performans etkisi nedir?
  31. Extension method'larda performans optimizasyonu nasıl yapılır?
  32. Extension method'lar memory kullanımını nasıl etkiler?

  33. Extension Method ve Best Practices

  34. Extension method yazarken dikkat edilmesi gerekenler nelerdir?
  35. Extension method isimlendirme kuralları nelerdir?
  36. Extension method'larda exception handling nasıl yapılır?

  37. Extension Method ve Framework Entegrasyonu

    • Extension method'lar framework'lerle nasıl entegre edilir?
    • Extension method'ların versioning'i nasıl yapılır?
    • Extension method'ların backward compatibility'si nasıl sağlanır?

Örnek Kod Soruları

  1. String Extension

    public static class StringExtensions
    {
        public static string Reverse(this string str)
        {
            // Implementasyon
        }
    }
    

  2. Collection Extension

    public static class CollectionExtensions
    {
        public static T GetRandomItem<T>(this IEnumerable<T> source)
        {
            // Implementasyon
        }
    }
    

  3. DateTime Extension

    public static class DateTimeExtensions
    {
        public static bool IsBusinessDay(this DateTime date)
        {
            // Implementasyon (hafta sonları ve resmi tatiller hariç)
        }
    }
    

  4. LINQ Extension

    public static class LinqExtensions
    {
        public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T> source)
        {
            // Implementasyon
        }
    }
    

  5. Validation Extension

    public static class ValidationExtensions
    {
        public static bool IsValidTurkishIdNumber(this string idNumber)
        {
            // Implementasyon
        }
    }
    

Kaynaklar