C# Özel Extension Metot Yazılışı ve Kullanımı

Kağan Saygın
2 min readJun 2, 2021

--

C# Projelerimizde sık sık Lambda İfadeleri (Lambda Expressions) extension metotlarını kullanıyoruz. Örneğin; .ToString(), ToLower(), ToUpper() gibi biz de kendimize özel uzantılarımızı oluşturabiliriz ve dll ile başka projelerimizde de kullanabiliriz.

Örnek olarak Kdv hesaplama yapacağız, console projesi oluşturuyoruz düzenli olması için;

  1. Extensions adlı bir klasör oluşturuyoruz,
  2. VatExtension adlı bir statik sınıf oluşturuyoruz,
  3. Kdv adında bir statik metot oluşturuyoruz.
public static class VatExtension
{
public static double Kdv(this double price, int vatRate)
{
//Tutara Kdv eklenmiş şekilde geri döndürür.
return price + (price * vatRate / 100);
}
}

Bu metodumuzu açıklayacak olursak double tipindeki değişkenlerin uzantılarında Kdv metodumuz gözükecektir.

this double price, double tipindeki işaretlenen sayıdır yani ürün fiyatımız aşağıdaki örnekte productPrice sayısıdır.

int vatRate, Kdv oranıdır parametre olarak dışarıdan alırız.

Kullanımı:

static void Main(string[] args)
{
double productPrice = 100;
Console.WriteLine(productPrice.Kdv(18));
}

Başka bir projede kullanmak için projemizde DLL dosyamızı kopyalıyoruz.

Diğer projemizde Visual Studioda

  1. Solution Explorer
  2. Dependencies
  3. Sağ Tık
  4. Add Project Reference
  5. Browse Dll Seçip OK

Bu işlemlerden sonra projemizde direkt kullanabiliriz.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response