Extension Metodların ilginç bi kullanımı BEnim çok hoşuma gitti. Sizler ne düşüneceksiniz bakalım

İlk Extension Metodumuzu yaratıyoruz

public static class FuncExtensions
{
public static TResult Catch<TExc, TResult>(this Func<TResult> func, Func<TExc, TResult> handleException) where TExc : Exception
{
try
{
return func();
}
catch (TExc ex)
{
return handleException(ex);
}
}
}

 

 

Artık  aşağıdaki kodu kullanmak yerine

int y;
try
{
y
= DoSomething();
}
catch (NullReferenceException ex)
{
y
= -1;
}

 

Artık bu kodu kullanabiliyoruz

int x = new Func<int>(DoSomething).Catch((NullReferenceException e) => -1);

Umarım hoşunuza gitmiştir