Skip to content

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
C#

C#: Use Expression-Bodied Members for Concise Single-Line Methods

- 30.03.26 - ErcanOPAK

➡️ Lambda-Style Everything

Simple methods with { return x; }? Verbose. Expression-bodied members use => for methods, properties, constructors. One line replaces five.

Expression-Bodied Methods

// ❌ Traditional method syntax
public string GetFullName()
{
    return $"{FirstName} {LastName}";
}

// ✅ Expression-bodied method
public string GetFullName() => $"{FirstName} {LastName}";

// More examples
public int Add(int a, int b) => a + b;

public bool IsAdult() => Age >= 18;

public void PrintMessage() => Console.WriteLine("Hello");

public async Task GetUserAsync(int id) => await _repository.GetByIdAsync(id);

🎯 Expression-Bodied Properties

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

    // ❌ Traditional read-only property
    public string FullName
    {
        get
        {
            return $"{FirstName} {LastName}";
        }
    }

    // ✅ Expression-bodied property
    public string FullName => $"{FirstName} {LastName}";

    // More examples
    public int Age => (int)((DateTime.Now - BirthDate).TotalDays / 365.25);
    
    public bool IsAdult => Age >= 18;
    
    public string Initials => $"{FirstName[0]}{LastName[0]}";
}

// Expression-bodied getter and setter (C# 7+)
private string _name;

public string Name
{
    get => _name;
    set => _name = value?.Trim() ?? throw new ArgumentNullException();
}

Expression-Bodied Constructors

public class Point
{
    public int X { get; }
    public int Y { get; }

    // ❌ Traditional constructor
    public Point(int x, int y)
    {
        X = x;
        Y = y;
    }

    // ✅ Expression-bodied constructor
    public Point(int x, int y) => (X, Y) = (x, y);
}

// More examples
public class Logger
{
    private readonly ILoggerFactory _factory;

    public Logger(ILoggerFactory factory) => _factory = factory ?? throw new ArgumentNullException(nameof(factory));
}

Expression-Bodied Finalizers & Indexers

// Expression-bodied finalizer
~MyClass() => Console.WriteLine("Finalizing");

// Expression-bodied indexer
public class Collection
{
    private readonly T[] _items;

    public Collection(T[] items) => _items = items;

    // ❌ Traditional indexer
    public T this[int index]
    {
        get { return _items[index]; }
        set { _items[index] = value; }
    }

    // ✅ Expression-bodied indexer
    public T this[int index]
    {
        get => _items[index];
        set => _items[index] = value;
    }
}

🔧 Complete Class Example

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public decimal Cost { get; set; }
    public int Stock { get; set; }

    // Expression-bodied properties
    public decimal Margin => Price - Cost;
    public decimal MarginPercent => (Margin / Price) * 100;
    public bool InStock => Stock > 0;
    public bool LowStock => Stock < 10 && Stock > 0;

    // Expression-bodied methods
    public decimal CalculateRevenue(int quantity) => Price * quantity;
    
    public decimal CalculateProfit(int quantity) => Margin * quantity;
    
    public bool CanFulfillOrder(int quantity) => Stock >= quantity;
    
    public void Restock(int amount) => Stock += amount;
    
    public void Sell(int quantity) => Stock -= quantity;

    // ToString
    public override string ToString() => $"Product: {Name} (${Price:F2})";
}

// Usage
var product = new Product 
{ 
    Name = "Widget", 
    Price = 100m, 
    Cost = 60m, 
    Stock = 50 
};

Console.WriteLine(product.Margin);         // 40
Console.WriteLine(product.MarginPercent);  // 40
Console.WriteLine(product.LowStock);       // false
Console.WriteLine(product.CalculateProfit(10));  // 400

✅ When to Use

  • Single-expression methods: One return statement
  • Read-only properties: Computed values
  • Simple getters/setters: Validation, transformation
  • Factory methods: new Constructor(params)
  • LINQ projections: Clean Select() statements

⚠️ When NOT to Use

  • Multiple statements: Stick to traditional syntax
  • Complex logic: Readability over conciseness
  • Long expressions: Line gets too long (> 120 chars)
  • Debugging: Can’t set breakpoint inside expression

💡 Before & After Comparison

// ❌ Before: 30 lines
public class Calculator
{
    public int Add(int a, int b)
    {
        return a + b;
    }

    public int Subtract(int a, int b)
    {
        return a - b;
    }

    public int Multiply(int a, int b)
    {
        return a * b;
    }

    public double Divide(int a, int b)
    {
        return (double)a / b;
    }

    public bool IsEven(int number)
    {
        return number % 2 == 0;
    }

    public int Square(int number)
    {
        return number * number;
    }
}

// ✅ After: 10 lines
public class Calculator
{
    public int Add(int a, int b) => a + b;
    public int Subtract(int a, int b) => a - b;
    public int Multiply(int a, int b) => a * b;
    public double Divide(int a, int b) => (double)a / b;
    public bool IsEven(int number) => number % 2 == 0;
    public int Square(int number) => number * number;
}

// 67% less code, same functionality!

“Refactored utility classes to expression-bodied members. Code reduced 40%. Readability improved. Team adopted it everywhere. Now standard in our style guide.”

— C# Developer

Related posts:

C#: Advanced LINQ Query Patterns for Complex Data

C#: Use ArrayPool to Reduce GC Pressure

C#: Use ValueTuple for Lightweight Multiple Return Values

Post Views: 15

Post navigation

C#: Enable Nullable Reference Types to Eliminate Null Reference Exceptions
C#: Use Init-Only Setters for Immutable Objects After Construction

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

October 2026
M T W T F S S
 1234
567891011
12131415161718
19202122232425
262728293031  
« Sep    

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (973)
  • How to make theater mode the default for Youtube (953)
  • How to add default value for Entity Framework migrations for DateTime and Bool (941)
  • Get the First and Last Word from a String or Sentence in SQL (847)
  • How to select distinct rows in a datatable in C# (837)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (624)
  • Add Constraint to SQL Table to ensure email contains @ (590)
  • Average of all values in a column that are not zero in SQL (554)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (526)
  • Find numbers with more than two decimal places in SQL (468)

Recent Posts

  • CSS: Fix a prefers-color-scheme Media Query That Gets Silently Overridden by a Browser Extension’s Forced Dark Mode
  • Git: Fix a Merge Commit That Silently Drops a File Because Both Branches Deleted It Differently
  • HTML5: Fix a Native Lazy-Loading Image That Never Loads Because It Sits Inside a Hidden Tab Until the User Clicks It
  • The AI Prompt That Traces a Null Reference Exception Back to the Exact Line That First Produced the Null
  • The AI Prompt That Turns a Gym Membership Contract’s Fine Print Into a Plain-English List of Cancellation Steps
  • Photoshop: Fix a Color Profile Mismatch That Makes Printed Output Look Nothing Like What You Saw On Screen
  • WordPress: Fix Search Results That Return Pages From a Theme You Deactivated Months Ago
  • Visual Studio: Fix a Test Project That Builds Fine Alone but Fails to Discover Any Tests After a NuGet Restore
  • ASP.NET Core: Fix a File Upload That Times Out on Slow Connections Only Because Kestrel’s Minimum Data Rate Feature Kicked In
  • JavaScript: Fix an Array Destructuring Default Value That Silently Never Applies Because null Was Passed Instead of Undefined

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (973)
  • How to make theater mode the default for Youtube (953)
  • How to add default value for Entity Framework migrations for DateTime and Bool (941)
  • Get the First and Last Word from a String or Sentence in SQL (847)
  • How to select distinct rows in a datatable in C# (837)

Recent Posts

  • CSS: Fix a prefers-color-scheme Media Query That Gets Silently Overridden by a Browser Extension’s Forced Dark Mode
  • Git: Fix a Merge Commit That Silently Drops a File Because Both Branches Deleted It Differently
  • HTML5: Fix a Native Lazy-Loading Image That Never Loads Because It Sits Inside a Hidden Tab Until the User Clicks It
  • The AI Prompt That Traces a Null Reference Exception Back to the Exact Line That First Produced the Null
  • The AI Prompt That Turns a Gym Membership Contract’s Fine Print Into a Plain-English List of Cancellation Steps

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com