<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>C# &#8211; Bits of .NET</title>
	<atom:link href="http://blog.ercanopak.com/category/c/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.ercanopak.com</link>
	<description>Daily micro-tips for C#, SQL, performance, and scalable backend engineering.</description>
	<lastBuildDate>Mon, 30 Mar 2026 17:52:20 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>http://blog.ercanopak.com/wp-content/uploads/2018/06/cropped-EO_LOGO_32-32x32.png</url>
	<title>C# &#8211; Bits of .NET</title>
	<link>http://blog.ercanopak.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>C#: Use Init-Only Setters for Immutable Objects After Construction</title>
		<link>http://blog.ercanopak.com/c-use-init-only-setters-for-immutable-objects-after-construction/</link>
					<comments>http://blog.ercanopak.com/c-use-init-only-setters-for-immutable-objects-after-construction/#respond</comments>
		
		<dc:creator><![CDATA[ErcanOPAK]]></dc:creator>
		<pubDate>Mon, 30 Mar 2026 17:52:20 +0000</pubDate>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[C# 11]]></category>
		<category><![CDATA[C# 9]]></category>
		<category><![CDATA[DTOs]]></category>
		<category><![CDATA[immutability]]></category>
		<category><![CDATA[Init-Only Setters]]></category>
		<category><![CDATA[Modern C#]]></category>
		<category><![CDATA[Object Initializers]]></category>
		<category><![CDATA[Required Members]]></category>
		<category><![CDATA[Value Objects]]></category>
		<guid isPermaLink="false">http://blog.ercanopak.com/c-use-init-only-setters-for-immutable-objects-after-construction/</guid>

					<description><![CDATA[🔒 Immutable After Creation Want immutable objects but like object initializers? Init-only setters (C# 9) allow setting properties during initialization only. Read-only after construction. The Old Dilemma // Option 1: Mutable properties (not safe) public class Person { public string Name { get; set; } public int Age { get; set; } } var person [&#8230;]]]></description>
										<content:encoded><![CDATA[<div style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); color: white; padding: 50px 40px; border-radius: 16px; margin: 40px 0; box-shadow: 0 20px 60px rgba(0,0,0,0.3);">
<h2 style="margin: 0 0 20px 0; font-size: 2.8em; font-weight: 800; line-height: 1.2;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f512.png" alt="🔒" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Immutable After Creation</h2>
<p style="font-size: 1.4em; line-height: 1.8; margin: 0; opacity: 0.95;">Want immutable objects but like object initializers? <strong>Init-only setters</strong> (C# 9) allow setting properties during initialization only. Read-only after construction.</p>
</p></div>
<h3 style="color: #2c3e50; font-size: 2.2em; margin: 50px 0 30px 0; font-weight: 700; border-left: 5px solid #f5576c; padding-left: 20px;">The Old Dilemma</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
// Option 1: Mutable properties (not safe)
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

var person = new Person { Name = "Alice", Age = 30 };
person.Age = 31;  // <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Works, but object is mutable

// Option 2: Read-only with constructor (verbose)
public class Person
{
    public string Name { get; }
    public int Age { get; }

    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }
}

var person = new Person("Alice", 30);  // Can't use object initializer <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" />

// Option 3: Private setter (still allows mutation in class)
public class Person
{
    public string Name { get; private set; }
    public int Age { get; private set; }
}

// All have tradeoffs!
</pre>
<h3 style="color: #2c3e50; font-size: 2.2em; margin: 50px 0 30px 0; font-weight: 700; border-left: 5px solid #27ae60; padding-left: 20px;">Init-Only Setters Solution</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
// <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Best of both worlds!
public class Person
{
    public string Name { get; init; }
    public int Age { get; init; }
}

// Can use object initializer
var person = new Person 
{ 
    Name = "Alice", 
    Age = 30 
};

// But can't modify after construction
person.Age = 31;  // <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Compile error: Init-only property can only be set in initializer

// Perfect for immutable objects!
</pre>
<div style="background: #f8f9fa; padding: 40px; border-radius: 12px; margin: 40px 0; border: 2px solid #f093fb;">
<h4 style="color: #f5576c; margin-top: 0; font-size: 1.7em; font-weight: 700;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f3af.png" alt="🎯" class="wp-smiley" style="height: 1em; max-height: 1em;" /> With Constructor</h4>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
public class Person
{
    public string Name { get; init; }
    public int Age { get; init; }
    public DateTime CreatedAt { get; init; }

    public Person()
    {
        CreatedAt = DateTime.UtcNow;  // <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Can set in constructor
    }
}

var person = new Person 
{ 
    Name = "Alice",
    Age = 30
};

Console.WriteLine(person.CreatedAt);  // Set automatically in constructor
// But CreatedAt can also be overridden in initializer if needed
</pre>
</p></div>
<h3 style="color: #2c3e50; font-size: 2.2em; margin: 50px 0 30px 0; font-weight: 700; border-left: 5px solid #667eea; padding-left: 20px;">Validation with Init</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
public class Email
{
    private string _value;

    public string Value
    {
        get => _value;
        init
        {
            if (string.IsNullOrWhiteSpace(value))
                throw new ArgumentException("Email cannot be empty");
            
            if (!value.Contains('@'))
                throw new ArgumentException("Invalid email format");
            
            _value = value;
        }
    }
}

var email = new Email { Value = "alice@example.com" };  // <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Valid
var invalid = new Email { Value = "not-an-email" };      // <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Throws exception

// After creation, immutable
// email.Value = "new@example.com";  // <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Compile error
</pre>
<h3 style="color: #2c3e50; font-size: 2.2em; margin: 50px 0 30px 0; font-weight: 700; border-left: 5px solid #f39c12; padding-left: 20px;">Required Members (C# 11)</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
// Combine init with required
public class User
{
    public required string Email { get; init; }
    public required string Name { get; init; }
    public string? PhoneNumber { get; init; }  // Optional
}

// <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Must set required properties
var user = new User 
{ 
    Email = "alice@example.com",
    Name = "Alice"
};

// <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Compile error: Required member 'Email' must be set
var invalid = new User { Name = "Alice" };
</pre>
<div style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); color: white; padding: 35px; border-radius: 12px; margin: 40px 0;">
<h4 style="margin-top: 0; font-size: 1.7em; font-weight: 700;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f310.png" alt="🌐" class="wp-smiley" style="height: 1em; max-height: 1em;" /> DTOs and API Models</h4>
<pre style="background: rgba(0,0,0,0.3); color: #fff; padding: 25px; border-radius: 8px; font-size: 1.05em; line-height: 1.8;">
// Perfect for API request/response DTOs
public class CreateUserRequest
{
    public required string Email { get; init; }
    public required string Password { get; init; }
    public required string Name { get; init; }
    public string? PhoneNumber { get; init; }
}

public class UserResponse
{
    public required int Id { get; init; }
    public required string Email { get; init; }
    public required string Name { get; init; }
    public required DateTime CreatedAt { get; init; }
}

// Controller
[HttpPost("users")]
public async Task<UserResponse> CreateUser(CreateUserRequest request)
{
    var user = await _userService.CreateAsync(request);
    
    return new UserResponse
    {
        Id = user.Id,
        Email = user.Email,
        Name = user.Name,
        CreatedAt = user.CreatedAt
    };
}

// Response is immutable - thread-safe!
</pre>
</p></div>
<h3 style="color: #2c3e50; font-size: 2.2em; margin: 50px 0 30px 0; font-weight: 700; border-left: 5px solid #27ae60; padding-left: 20px;">With Record Types</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
// Records have init by default
public record Person(string Name, int Age);

// Same as:
public record Person
{
    public string Name { get; init; }
    public int Age { get; init; }
    
    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }
}

// Use with expressions for non-destructive mutation
var person1 = new Person("Alice", 30);
var person2 = person1 with { Age = 31 };

// person1 unchanged, person2 has new age
</pre>
<div style="background: linear-gradient(135deg, #d4edda 0%, #c3e6cb 100%); padding: 35px; border-radius: 12px; margin: 40px 0; border-left: 5px solid #28a745;">
<h4 style="color: #155724; margin-top: 0; font-size: 1.7em; font-weight: 700;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Benefits</h4>
<ul style="color: #155724; font-size: 1.15em; line-height: 2.2; margin: 20px 0;">
<li><strong>Object initializer syntax:</strong> Clean, readable</li>
<li><strong>Immutability:</strong> Thread-safe, predictable</li>
<li><strong>Required members:</strong> Compiler enforces initialization</li>
<li><strong>Validation:</strong> Can validate in init setter</li>
<li><strong>No constructor bloat:</strong> Avoid 10-parameter constructors</li>
</ul></div>
<div style="background: linear-gradient(135deg, #fff3cd 0%, #ffe69c 100%); border-left: 5px solid #ffc107; padding: 35px; margin: 50px 0; border-radius: 12px;">
<h4 style="color: #856404; margin-top: 0; font-size: 1.7em; font-weight: 700;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Best Practices</h4>
<ul style="color: #856404; font-size: 1.15em; line-height: 2.2; margin: 20px 0;">
<li><strong>Use for DTOs:</strong> API models, configuration objects</li>
<li><strong>Combine with required:</strong> Enforce mandatory properties</li>
<li><strong>Add validation:</strong> In init setters when needed</li>
<li><strong>Prefer records:</strong> For data-centric types</li>
<li><strong>Document intent:</strong> Use init to signal immutability</li>
</ul></div>
<div style="background: #f8f9fa; padding: 40px; border-radius: 12px; margin: 40px 0; border: 2px solid #f093fb;">
<h4 style="color: #f5576c; margin-top: 0; font-size: 1.7em; font-weight: 700;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f3af.png" alt="🎯" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Real-World Example</h4>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
// Configuration object
public class DatabaseConfig
{
    public required string ConnectionString { get; init; }
    public required string DatabaseName { get; init; }
    public int MaxPoolSize { get; init; } = 100;
    public int CommandTimeout { get; init; } = 30;
    public bool EnableRetry { get; init; } = true;
}

// Usage
var config = new DatabaseConfig
{
    ConnectionString = "Server=localhost;Database=mydb",
    DatabaseName = "mydb",
    MaxPoolSize = 200
};

// Immutable after creation - safe to pass around
await InitializeDatabaseAsync(config);

// Can't accidentally change config
// config.MaxPoolSize = 300;  // <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Compile error

// Value object
public class Money
{
    public required decimal Amount { get; init; }
    public required string Currency { get; init; }

    public Money Add(Money other)
    {
        if (Currency != other.Currency)
            throw new InvalidOperationException("Currency mismatch");
        
        return new Money 
        { 
            Amount = Amount + other.Amount,
            Currency = Currency
        };
    }
}

var price1 = new Money { Amount = 100m, Currency = "USD" };
var price2 = new Money { Amount = 50m, Currency = "USD" };
var total = price1.Add(price2);

// All Money objects immutable - safe!
</pre>
</p></div>
<blockquote style="background: linear-gradient(to right, #fce4ec, #f8bbd0); border-left: 6px solid #e91e63; padding: 40px; margin: 50px 0; border-radius: 12px;">
<p style="font-size: 1.5em; line-height: 1.9; margin: 0; color: #880e4f; font-style: italic; font-weight: 500;">&#8220;Converted all configuration classes to init-only properties. Thread-safety bugs disappeared. Code cleaner with object initializers. Required keyword catches missing configs at compile-time.&#8221;</p>
<footer style="margin-top: 20px; color: #ad1457; font-size: 1.15em; font-weight: 600;">— Senior .NET Engineer</footer>
</blockquote>
]]></content:encoded>
					
					<wfw:commentRss>http://blog.ercanopak.com/c-use-init-only-setters-for-immutable-objects-after-construction/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>C#: Use Expression-Bodied Members for Concise Single-Line Methods</title>
		<link>http://blog.ercanopak.com/c-use-expression-bodied-members-for-concise-single-line-methods/</link>
					<comments>http://blog.ercanopak.com/c-use-expression-bodied-members-for-concise-single-line-methods/#respond</comments>
		
		<dc:creator><![CDATA[ErcanOPAK]]></dc:creator>
		<pubDate>Mon, 30 Mar 2026 17:52:14 +0000</pubDate>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[C# 6]]></category>
		<category><![CDATA[C# 7]]></category>
		<category><![CDATA[C# Tips]]></category>
		<category><![CDATA[Clean Code]]></category>
		<category><![CDATA[Code Style]]></category>
		<category><![CDATA[Concise Code]]></category>
		<category><![CDATA[Expression-Bodied Members]]></category>
		<category><![CDATA[Lambda Expressions]]></category>
		<category><![CDATA[Modern C#]]></category>
		<guid isPermaLink="false">http://blog.ercanopak.com/c-use-expression-bodied-members-for-concise-single-line-methods/</guid>

					<description><![CDATA[➡️ 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, [&#8230;]]]></description>
										<content:encoded><![CDATA[<div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 50px 40px; border-radius: 16px; margin: 40px 0; box-shadow: 0 20px 60px rgba(0,0,0,0.3);">
<h2 style="margin: 0 0 20px 0; font-size: 2.8em; font-weight: 800; line-height: 1.2;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/27a1.png" alt="➡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Lambda-Style Everything</h2>
<p style="font-size: 1.4em; line-height: 1.8; margin: 0; opacity: 0.95;">Simple methods with { return x; }? Verbose. <strong>Expression-bodied members</strong> use => for methods, properties, constructors. One line replaces five.</p>
</p></div>
<h3 style="color: #2c3e50; font-size: 2.2em; margin: 50px 0 30px 0; font-weight: 700; border-left: 5px solid #764ba2; padding-left: 20px;">Expression-Bodied Methods</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
// <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Traditional method syntax
public string GetFullName()
{
    return $"{FirstName} {LastName}";
}

// <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> 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<User> GetUserAsync(int id) => await _repository.GetByIdAsync(id);
</pre>
<div style="background: #f8f9fa; padding: 40px; border-radius: 12px; margin: 40px 0; border: 2px solid #667eea;">
<h4 style="color: #667eea; margin-top: 0; font-size: 1.7em; font-weight: 700;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f3af.png" alt="🎯" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Expression-Bodied Properties</h4>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime BirthDate { get; set; }

    // <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Traditional read-only property
    public string FullName
    {
        get
        {
            return $"{FirstName} {LastName}";
        }
    }

    // <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> 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();
}
</pre>
</p></div>
<h3 style="color: #2c3e50; font-size: 2.2em; margin: 50px 0 30px 0; font-weight: 700; border-left: 5px solid #f39c12; padding-left: 20px;">Expression-Bodied Constructors</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
public class Point
{
    public int X { get; }
    public int Y { get; }

    // <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Traditional constructor
    public Point(int x, int y)
    {
        X = x;
        Y = y;
    }

    // <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> 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));
}
</pre>
<h3 style="color: #2c3e50; font-size: 2.2em; margin: 50px 0 30px 0; font-weight: 700; border-left: 5px solid #27ae60; padding-left: 20px;">Expression-Bodied Finalizers &#038; Indexers</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
// Expression-bodied finalizer
~MyClass() => Console.WriteLine("Finalizing");

// Expression-bodied indexer
public class Collection<T>
{
    private readonly T[] _items;

    public Collection(T[] items) => _items = items;

    // <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Traditional indexer
    public T this[int index]
    {
        get { return _items[index]; }
        set { _items[index] = value; }
    }

    // <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Expression-bodied indexer
    public T this[int index]
    {
        get => _items[index];
        set => _items[index] = value;
    }
}
</pre>
<div style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); color: white; padding: 35px; border-radius: 12px; margin: 40px 0;">
<h4 style="margin-top: 0; font-size: 1.7em; font-weight: 700;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f527.png" alt="🔧" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Complete Class Example</h4>
<pre style="background: rgba(0,0,0,0.3); color: #fff; padding: 25px; border-radius: 8px; font-size: 1.05em; line-height: 1.8;">
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 &#038;&#038; 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
</pre>
</p></div>
<div style="background: linear-gradient(135deg, #d4edda 0%, #c3e6cb 100%); padding: 35px; border-radius: 12px; margin: 40px 0; border-left: 5px solid #28a745;">
<h4 style="color: #155724; margin-top: 0; font-size: 1.7em; font-weight: 700;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> When to Use</h4>
<ul style="color: #155724; font-size: 1.15em; line-height: 2.2; margin: 20px 0;">
<li><strong>Single-expression methods:</strong> One return statement</li>
<li><strong>Read-only properties:</strong> Computed values</li>
<li><strong>Simple getters/setters:</strong> Validation, transformation</li>
<li><strong>Factory methods:</strong> new Constructor(params)</li>
<li><strong>LINQ projections:</strong> Clean Select() statements</li>
</ul></div>
<div style="background: linear-gradient(135deg, #fff3cd 0%, #ffe69c 100%); border-left: 5px solid #ffc107; padding: 35px; margin: 50px 0; border-radius: 12px;">
<h4 style="color: #856404; margin-top: 0; font-size: 1.7em; font-weight: 700;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/26a0.png" alt="⚠" class="wp-smiley" style="height: 1em; max-height: 1em;" /> When NOT to Use</h4>
<ul style="color: #856404; font-size: 1.15em; line-height: 2.2; margin: 20px 0;">
<li><strong>Multiple statements:</strong> Stick to traditional syntax</li>
<li><strong>Complex logic:</strong> Readability over conciseness</li>
<li><strong>Long expressions:</strong> Line gets too long (> 120 chars)</li>
<li><strong>Debugging:</strong> Can&#8217;t set breakpoint inside expression</li>
</ul></div>
<div style="background: #f8f9fa; padding: 40px; border-radius: 12px; margin: 40px 0; border: 2px solid #667eea;">
<h4 style="color: #667eea; margin-top: 0; font-size: 1.7em; font-weight: 700;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Before &#038; After Comparison</h4>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
// <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" /> 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;
    }
}

// <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> 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!
</pre>
</p></div>
<blockquote style="background: linear-gradient(to right, #e8eaf6, #c5cae9); border-left: 6px solid #5c6bc0; padding: 40px; margin: 50px 0; border-radius: 12px;">
<p style="font-size: 1.5em; line-height: 1.9; margin: 0; color: #1a237e; font-style: italic; font-weight: 500;">&#8220;Refactored utility classes to expression-bodied members. Code reduced 40%. Readability improved. Team adopted it everywhere. Now standard in our style guide.&#8221;</p>
<footer style="margin-top: 20px; color: #283593; font-size: 1.15em; font-weight: 600;">— C# Developer</footer>
</blockquote>
]]></content:encoded>
					
					<wfw:commentRss>http://blog.ercanopak.com/c-use-expression-bodied-members-for-concise-single-line-methods/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>C#: Enable Nullable Reference Types to Eliminate Null Reference Exceptions</title>
		<link>http://blog.ercanopak.com/c-enable-nullable-reference-types-to-eliminate-null-reference-exceptions/</link>
					<comments>http://blog.ercanopak.com/c-enable-nullable-reference-types-to-eliminate-null-reference-exceptions/#respond</comments>
		
		<dc:creator><![CDATA[ErcanOPAK]]></dc:creator>
		<pubDate>Mon, 30 Mar 2026 17:52:07 +0000</pubDate>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[C# 8]]></category>
		<category><![CDATA[Code Quality]]></category>
		<category><![CDATA[Compiler Warnings]]></category>
		<category><![CDATA[Modern C#]]></category>
		<category><![CDATA[Null Safety]]></category>
		<category><![CDATA[Nullable Reference Types]]></category>
		<category><![CDATA[NullReferenceException]]></category>
		<category><![CDATA[Type Safety]]></category>
		<guid isPermaLink="false">http://blog.ercanopak.com/c-enable-nullable-reference-types-to-eliminate-null-reference-exceptions/</guid>

					<description><![CDATA[🛡️ No More NullReferenceException NullReferenceException killing your app? Can&#8217;t tell if variable can be null? Nullable reference types (C# 8+) make nullability explicit. Compiler warns about potential null errors. The Null Problem // Before nullable reference types public class UserService { public string GetUserName(int userId) { var user = _repository.GetById(userId); // Could return null! return [&#8230;]]]></description>
										<content:encoded><![CDATA[<div style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); color: white; padding: 50px 40px; border-radius: 16px; margin: 40px 0; box-shadow: 0 20px 60px rgba(0,0,0,0.3);">
<h2 style="margin: 0 0 20px 0; font-size: 2.8em; font-weight: 800; line-height: 1.2;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f6e1.png" alt="🛡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> No More NullReferenceException</h2>
<p style="font-size: 1.4em; line-height: 1.8; margin: 0; opacity: 0.95;">NullReferenceException killing your app? Can&#8217;t tell if variable can be null? <strong>Nullable reference types</strong> (C# 8+) make nullability explicit. Compiler warns about potential null errors.</p>
</p></div>
<h3 style="color: #2c3e50; font-size: 2.2em; margin: 50px 0 30px 0; font-weight: 700; border-left: 5px solid #00f2fe; padding-left: 20px;">The Null Problem</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
// Before nullable reference types
public class UserService
{
    public string GetUserName(int userId)
    {
        var user = _repository.GetById(userId);  // Could return null!
        return user.Name;  // <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a5.png" alt="💥" class="wp-smiley" style="height: 1em; max-height: 1em;" /> NullReferenceException if user is null
    }
}

// No compiler warning!
// Crashes at runtime
// "The billion dollar mistake" - Tony Hoare
</pre>
<h3 style="color: #2c3e50; font-size: 2.2em; margin: 50px 0 30px 0; font-weight: 700; border-left: 5px solid #27ae60; padding-left: 20px;">Enable Nullable Reference Types</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="xml">
<!-- In .csproj -->
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <Nullable>enable</Nullable>  <!-- Enable nullable warnings -->
  </PropertyGroup>
</Project>

<!-- Or in specific files -->
#nullable enable  // At top of .cs file
</pre>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
// After enabling nullable reference types
public class UserService
{
    // Non-nullable: Must never be null
    public string GetUserName(int userId)
    {
        User? user = _repository.GetById(userId);  // User? = nullable
        return user.Name;  // <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/26a0.png" alt="⚠" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Compiler warning: Possible null reference
    }
    
    // Fixed version
    public string GetUserName(int userId)
    {
        User? user = _repository.GetById(userId);
        
        if (user == null)
        {
            throw new UserNotFoundException(userId);
        }
        
        return user.Name;  // <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> No warning - null checked
    }
    
    // Or return nullable
    public string? GetUserName(int userId)
    {
        User? user = _repository.GetById(userId);
        return user?.Name;  // <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Returns null if user is null
    }
}
</pre>
<div style="background: #f8f9fa; padding: 40px; border-radius: 12px; margin: 40px 0; border: 2px solid #4facfe;">
<h4 style="color: #00f2fe; margin-top: 0; font-size: 1.7em; font-weight: 700;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f3af.png" alt="🎯" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Nullable Syntax</h4>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
// Non-nullable reference type (default)
string name = "Alice";
name = null;  // <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/26a0.png" alt="⚠" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Warning: Cannot assign null

// Nullable reference type (explicit ?)
string? name = null;  // <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> OK
name = "Alice";      // <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> OK

// Non-nullable in method signatures
public void ProcessUser(User user)  // user cannot be null
{
    Console.WriteLine(user.Name);  // <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> No null check needed
}

// Nullable in method signatures
public void ProcessUser(User? user)  // user might be null
{
    if (user != null)
    {
        Console.WriteLine(user.Name);  // <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Null checked
    }
}

// Return types
public User GetUser(int id)      // Never returns null
public User? FindUser(int id)    // Might return null
</pre>
</p></div>
<h3 style="color: #2c3e50; font-size: 2.2em; margin: 50px 0 30px 0; font-weight: 700; border-left: 5px solid #667eea; padding-left: 20px;">Null-Handling Patterns</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
User? user = FindUser(123);

// 1. Null check
if (user != null)
{
    Console.WriteLine(user.Name);
}

// 2. Null-conditional operator
Console.WriteLine(user?.Name);  // Returns null if user is null

// 3. Null-coalescing operator
string name = user?.Name ?? "Unknown";

// 4. Throw if null
User nonNullUser = user ?? throw new ArgumentNullException(nameof(user));

// 5. Pattern matching
if (user is { Name: var name })
{
    Console.WriteLine(name);  // user is not null here
}

// 6. Null-forgiving operator (! - use sparingly!)
Console.WriteLine(user!.Name);  // Tell compiler: "I know it's not null"
// Use only when you're 100% sure
</pre>
<h3 style="color: #2c3e50; font-size: 2.2em; margin: 50px 0 30px 0; font-weight: 700; border-left: 5px solid #f39c12; padding-left: 20px;">Constructor and Property Initialization</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
public class User
{
    // <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/26a0.png" alt="⚠" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Warning: Non-nullable property must be initialized
    public string Name { get; set; }
    
    // <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Fixed: Initialize in constructor
    public User(string name)
    {
        Name = name;
    }
}

// Or use required (C# 11)
public class User
{
    public required string Name { get; set; }
    public string? Email { get; set; }  // Optional, can be null
}

var user = new User { Name = "Alice" };  // <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> OK
var user2 = new User { Email = "test@example.com" };  // <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/26a0.png" alt="⚠" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Error: Name required

// Or default value
public class User
{
    public string Name { get; set; } = string.Empty;
    public List<Order> Orders { get; set; } = new();
}
</pre>
<div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 35px; border-radius: 12px; margin: 40px 0;">
<h4 style="margin-top: 0; font-size: 1.7em; font-weight: 700;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f527.png" alt="🔧" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Suppress Warnings (When Needed)</h4>
<pre style="background: rgba(0,0,0,0.3); color: #fff; padding: 25px; border-radius: 8px; font-size: 1.05em; line-height: 1.8;">
// Null-forgiving operator !
string GetName(User? user)
{
    // You KNOW user is not null (e.g., validated earlier)
    return user!.Name;  // Suppresses warning
}

// Pragma directive (suppress for block)
#pragma warning disable CS8600  // Converting null literal
string? name = null;
#pragma warning restore CS8600

// Attribute (for methods that ensure non-null)
public static bool TryGetUser(int id, [NotNullWhen(true)] out User? user)
{
    user = FindUser(id);
    return user != null;
}

if (TryGetUser(123, out var user))
{
    Console.WriteLine(user.Name);  // <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Compiler knows user is not null
}
</pre>
</p></div>
<div style="background: linear-gradient(135deg, #d4edda 0%, #c3e6cb 100%); padding: 35px; border-radius: 12px; margin: 40px 0; border-left: 5px solid #28a745;">
<h4 style="color: #155724; margin-top: 0; font-size: 1.7em; font-weight: 700;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Benefits</h4>
<ul style="color: #155724; font-size: 1.15em; line-height: 2.2; margin: 20px 0;">
<li><strong>Catch bugs early:</strong> At compile-time, not runtime</li>
<li><strong>Self-documenting:</strong> API clearly shows what can be null</li>
<li><strong>Better tooling:</strong> IDE shows nullable warnings</li>
<li><strong>Safer code:</strong> Forces you to handle null cases</li>
<li><strong>Fewer crashes:</strong> NullReferenceException reduced dramatically</li>
</ul></div>
<div style="background: linear-gradient(135deg, #fff3cd 0%, #ffe69c 100%); border-left: 5px solid #ffc107; padding: 35px; margin: 50px 0; border-radius: 12px;">
<h4 style="color: #856404; margin-top: 0; font-size: 1.7em; font-weight: 700;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Migration Strategy</h4>
<ul style="color: #856404; font-size: 1.15em; line-height: 2.2; margin: 20px 0;">
<li><strong>Enable gradually:</strong> Per-file with #nullable enable</li>
<li><strong>Start with new code:</strong> Don&#8217;t rewrite everything at once</li>
<li><strong>Fix warnings systematically:</strong> Don&#8217;t suppress blindly</li>
<li><strong>Use analyzers:</strong> Enable all nullable warnings</li>
<li><strong>Team buy-in:</strong> Everyone must understand nullable</li>
</ul></div>
<div style="background: #f8f9fa; padding: 40px; border-radius: 12px; margin: 40px 0; border: 2px solid #4facfe;">
<h4 style="color: #00f2fe; margin-top: 0; font-size: 1.7em; font-weight: 700;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f3af.png" alt="🎯" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Real-World Example</h4>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
#nullable enable

public class OrderService
{
    private readonly IOrderRepository _repository;
    private readonly IEmailService _emailService;

    public OrderService(IOrderRepository repository, IEmailService emailService)
    {
        _repository = repository;
        _emailService = emailService;
    }

    // Clear contract: Never returns null
    public Order GetOrder(int id)
    {
        Order? order = _repository.FindById(id);
        
        if (order == null)
        {
            throw new OrderNotFoundException($"Order {id} not found");
        }
        
        return order;  // <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Guaranteed non-null
    }

    // Clear contract: Might return null
    public Order? FindOrder(int id)
    {
        return _repository.FindById(id);  // <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Nullable return
    }

    public async Task ProcessOrder(Order order, string? promoCode)
    {
        // order is non-nullable - no need to check
        order.Status = OrderStatus.Processing;

        // promoCode is nullable - must check
        if (promoCode != null)
        {
            ApplyPromoCode(order, promoCode);
        }

        await _repository.SaveAsync(order);
        
        // Email might be null, handle gracefully
        await _emailService.SendConfirmationAsync(order.CustomerEmail ?? "no-reply@store.com");
    }
}
</pre>
</p></div>
<blockquote style="background: linear-gradient(to right, #e0f7fa, #b2ebf2); border-left: 6px solid #00bcd4; padding: 40px; margin: 50px 0; border-radius: 12px;">
<p style="font-size: 1.5em; line-height: 1.9; margin: 0; color: #006064; font-style: italic; font-weight: 500;">&#8220;Enabled nullable reference types on legacy codebase. Compiler found 147 potential null bugs. Fixed them all. NullReferenceException crashes dropped 95%. Best decision for code quality.&#8221;</p>
<footer style="margin-top: 20px; color: #00838f; font-size: 1.15em; font-weight: 600;">— Tech Lead</footer>
</blockquote>
]]></content:encoded>
					
					<wfw:commentRss>http://blog.ercanopak.com/c-enable-nullable-reference-types-to-eliminate-null-reference-exceptions/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>C#: Use Record Types for Immutable Data Objects</title>
		<link>http://blog.ercanopak.com/c-use-record-types-for-immutable-data-objects/</link>
					<comments>http://blog.ercanopak.com/c-use-record-types-for-immutable-data-objects/#respond</comments>
		
		<dc:creator><![CDATA[ErcanOPAK]]></dc:creator>
		<pubDate>Mon, 30 Mar 2026 17:52:00 +0000</pubDate>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[C# 9]]></category>
		<category><![CDATA[C# Tips]]></category>
		<category><![CDATA[Data Classes]]></category>
		<category><![CDATA[DTOs]]></category>
		<category><![CDATA[immutability]]></category>
		<category><![CDATA[Modern C#]]></category>
		<category><![CDATA[Pattern Matching]]></category>
		<category><![CDATA[Record Types]]></category>
		<category><![CDATA[Value Objects]]></category>
		<guid isPermaLink="false">http://blog.ercanopak.com/c-use-record-types-for-immutable-data-objects/</guid>

					<description><![CDATA[📦 Value Objects Made Easy DTOs with 50 lines of boilerplate? Equals(), GetHashCode(), ToString()? Record types (C# 9+) are immutable, value-based, with auto-generated methods. One line replaces 50. Traditional Class vs Record // ❌ Traditional class - Lots of boilerplate public class PersonClass { public string Name { get; init; } public int Age { [&#8230;]]]></description>
										<content:encoded><![CDATA[<div style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); color: white; padding: 50px 40px; border-radius: 16px; margin: 40px 0; box-shadow: 0 20px 60px rgba(0,0,0,0.3);">
<h2 style="margin: 0 0 20px 0; font-size: 2.8em; font-weight: 800; line-height: 1.2;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4e6.png" alt="📦" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Value Objects Made Easy</h2>
<p style="font-size: 1.4em; line-height: 1.8; margin: 0; opacity: 0.95;">DTOs with 50 lines of boilerplate? Equals(), GetHashCode(), ToString()? <strong>Record types</strong> (C# 9+) are immutable, value-based, with auto-generated methods. One line replaces 50.</p>
</p></div>
<h3 style="color: #2c3e50; font-size: 2.2em; margin: 50px 0 30px 0; font-weight: 700; border-left: 5px solid #f5576c; padding-left: 20px;">Traditional Class vs Record</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
// <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Traditional class - Lots of boilerplate
public class PersonClass
{
    public string Name { get; init; }
    public int Age { get; init; }
    
    public PersonClass(string name, int age)
    {
        Name = name;
        Age = age;
    }
    
    // Manual Equals
    public override bool Equals(object? obj)
    {
        if (obj is not PersonClass other) return false;
        return Name == other.Name && Age == other.Age;
    }
    
    // Manual GetHashCode
    public override int GetHashCode()
    {
        return HashCode.Combine(Name, Age);
    }
    
    // Manual ToString
    public override string ToString()
    {
        return $"PersonClass {{ Name = {Name}, Age = {Age} }}";
    }
    
    // Manual copy with changes
    public PersonClass WithAge(int newAge)
    {
        return new PersonClass(Name, newAge);
    }
}

// 40+ lines for simple data object!

// <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Record - One line!
public record Person(string Name, int Age);

// That's it! Auto-generates:
// - Constructor
// - Properties (init-only)
// - Equals() and GetHashCode() (value-based)
// - ToString()
// - Deconstruct()
// - With expressions
</pre>
<div style="background: #f8f9fa; padding: 40px; border-radius: 12px; margin: 40px 0; border: 2px solid #f093fb;">
<h4 style="color: #f5576c; margin-top: 0; font-size: 1.7em; font-weight: 700;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f3af.png" alt="🎯" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Record Features</h4>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
public record Person(string Name, int Age);

// Value-based equality
var person1 = new Person("Alice", 30);
var person2 = new Person("Alice", 30);

Console.WriteLine(person1 == person2);  // True! (value equality)
// With classes: False (reference equality)

// Auto ToString()
Console.WriteLine(person1);  // Person { Name = Alice, Age = 30 }

// With expressions (non-destructive mutation)
var person3 = person1 with { Age = 31 };
Console.WriteLine(person3);  // Person { Name = Alice, Age = 31 }
// person1 unchanged (immutable)

// Deconstruction
var (name, age) = person1;
Console.WriteLine($"{name} is {age}");  // Alice is 30

// Pattern matching
var message = person1 switch
{
    { Age: < 18 } => "Minor",
    { Age: >= 18 and < 65 } => "Adult",
    _ => "Senior"
};
</pre>
</p></div>
<h3 style="color: #2c3e50; font-size: 2.2em; margin: 50px 0 30px 0; font-weight: 700; border-left: 5px solid #667eea; padding-left: 20px;">Record vs Record Struct vs Class</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
// Record (reference type, immutable by default)
public record Person(string Name, int Age);

// Record struct (value type, C# 10+)
public record struct Point(int X, int Y);

// Class (reference type, mutable)
public class PersonClass
{
    public string Name { get; set; }
    public int Age { get; set; }
}

// When to use what?
// Record: DTOs, value objects, immutable data
// Record struct: Small data (< 16 bytes), high-performance scenarios
// Class: Entities with behavior, mutable state
</pre>
<h3 style="color: #2c3e50; font-size: 2.2em; margin: 50px 0 30px 0; font-weight: 700; border-left: 5px solid #f39c12; padding-left: 20px;">Advanced Record Features</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
// Additional properties and methods
public record Person(string Name, int Age)
{
    // Computed property
    public string DisplayName => $"{Name} ({Age})";
    
    // Validation
    public Person
    {
        if (Age < 0) throw new ArgumentException("Age cannot be negative");
    }
    
    // Additional methods
    public bool IsAdult() => Age >= 18;
}

// Inheritance (records can inherit from records)
public record Employee(string Name, int Age, string Department) 
    : Person(Name, Age);

var emp = new Employee("Bob", 25, "IT");
Console.WriteLine(emp);  
// Employee { Name = Bob, Age = 25, Department = IT }

// With expression works with derived records
var emp2 = emp with { Department = "HR" };
</pre>
<div style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); color: white; padding: 35px; border-radius: 12px; margin: 40px 0;">
<h4 style="margin-top: 0; font-size: 1.7em; font-weight: 700;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f310.png" alt="🌐" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Perfect for DTOs</h4>
<pre style="background: rgba(0,0,0,0.3); color: #fff; padding: 25px; border-radius: 8px; font-size: 1.05em; line-height: 1.8;">
// API Request/Response DTOs
public record CreateUserRequest(
    string Email,
    string Name,
    string Password
);

public record UserResponse(
    int Id,
    string Email,
    string Name,
    DateTime CreatedAt
);

// API Controller
[HttpPost("users")]
public async Task<UserResponse> CreateUser(CreateUserRequest request)
{
    var user = await _userService.CreateAsync(request);
    return new UserResponse(
        user.Id,
        user.Email,
        user.Name,
        user.CreatedAt
    );
}

// Clean, immutable, perfect for data transfer
</pre>
</p></div>
<h3 style="color: #2c3e50; font-size: 2.2em; margin: 50px 0 30px 0; font-weight: 700; border-left: 5px solid #27ae60; padding-left: 20px;">Positional vs Nominal Records</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
// Positional record (concise)
public record Person(string Name, int Age);

// Nominal record (traditional property syntax)
public record Person
{
    public string Name { get; init; }
    public int Age { get; init; }
}

// Mix both
public record Person(string Name, int Age)
{
    public string Email { get; init; } = string.Empty;
    public DateTime CreatedAt { get; init; } = DateTime.UtcNow;
}

var person = new Person("Alice", 30)
{
    Email = "alice@example.com"
};
</pre>
<div style="background: linear-gradient(135deg, #d4edda 0%, #c3e6cb 100%); padding: 35px; border-radius: 12px; margin: 40px 0; border-left: 5px solid #28a745;">
<h4 style="color: #155724; margin-top: 0; font-size: 1.7em; font-weight: 700;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Benefits of Records</h4>
<ul style="color: #155724; font-size: 1.15em; line-height: 2.2; margin: 20px 0;">
<li><strong>Less code:</strong> 90% less boilerplate than classes</li>
<li><strong>Immutable by default:</strong> Thread-safe, predictable</li>
<li><strong>Value semantics:</strong> Equality based on data, not reference</li>
<li><strong>With expressions:</strong> Easy non-destructive updates</li>
<li><strong>Pattern matching:</strong> Works beautifully with switch</li>
<li><strong>Auto ToString():</strong> Great for debugging</li>
</ul></div>
<div style="background: linear-gradient(135deg, #fff3cd 0%, #ffe69c 100%); border-left: 5px solid #ffc107; padding: 35px; margin: 50px 0; border-radius: 12px;">
<h4 style="color: #856404; margin-top: 0; font-size: 1.7em; font-weight: 700;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Best Practices</h4>
<ul style="color: #856404; font-size: 1.15em; line-height: 2.2; margin: 20px 0;">
<li><strong>Use for DTOs:</strong> API requests/responses, messages</li>
<li><strong>Use for value objects:</strong> Money, Address, Coordinate</li>
<li><strong>Add validation:</strong> In constructor or properties</li>
<li><strong>Keep immutable:</strong> Use init, not set</li>
<li><strong>Prefer positional:</strong> More concise for simple records</li>
</ul></div>
<div style="background: #f8f9fa; padding: 40px; border-radius: 12px; margin: 40px 0; border: 2px solid #f093fb;">
<h4 style="color: #f5576c; margin-top: 0; font-size: 1.7em; font-weight: 700;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f3af.png" alt="🎯" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Real-World Example</h4>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
// Domain value objects
public record Money(decimal Amount, string Currency)
{
    public Money Add(Money other)
    {
        if (Currency != other.Currency)
            throw new InvalidOperationException("Currency mismatch");
        return this with { Amount = Amount + other.Amount };
    }
}

public record Address(
    string Street,
    string City,
    string State,
    string ZipCode,
    string Country
);

public record CustomerDto(
    int Id,
    string Name,
    Address Address,
    Money Balance
);

// Usage
var addr = new Address("123 Main St", "NYC", "NY", "10001", "USA");
var balance = new Money(1000m, "USD");
var customer = new CustomerDto(1, "Alice", addr, balance);

// Update address
var updated = customer with 
{ 
    Address = customer.Address with { City = "Boston" }
};

// Value equality
var addr2 = new Address("123 Main St", "NYC", "NY", "10001", "USA");
Console.WriteLine(addr == addr2);  // True!
</pre>
</p></div>
<blockquote style="background: linear-gradient(to right, #fce4ec, #f8bbd0); border-left: 6px solid #e91e63; padding: 40px; margin: 50px 0; border-radius: 12px;">
<p style="font-size: 1.5em; line-height: 1.9; margin: 0; color: #880e4f; font-style: italic; font-weight: 500;">"Converted all DTOs from classes to records. Deleted 2000+ lines of boilerplate. Bugs related to mutable state disappeared. API responses now immutable, thread-safe. Should've used records from day one."</p>
<footer style="margin-top: 20px; color: #ad1457; font-size: 1.15em; font-weight: 600;">— .NET Developer</footer>
</blockquote>
]]></content:encoded>
					
					<wfw:commentRss>http://blog.ercanopak.com/c-use-record-types-for-immutable-data-objects/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>C#: Use Span for High-Performance Memory Operations</title>
		<link>http://blog.ercanopak.com/c-use-span-for-high-performance-memory-operations/</link>
					<comments>http://blog.ercanopak.com/c-use-span-for-high-performance-memory-operations/#respond</comments>
		
		<dc:creator><![CDATA[ErcanOPAK]]></dc:creator>
		<pubDate>Sun, 22 Mar 2026 09:05:49 +0000</pubDate>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[C# 7.2]]></category>
		<category><![CDATA[High Performance]]></category>
		<category><![CDATA[memory]]></category>
		<category><![CDATA[Memory Management]]></category>
		<category><![CDATA[Modern C#]]></category>
		<category><![CDATA[span]]></category>
		<category><![CDATA[stackalloc]]></category>
		<category><![CDATA[Zero Allocation]]></category>
		<guid isPermaLink="false">http://blog.ercanopak.com/c-use-span-for-high-performance-memory-operations/</guid>

					<description><![CDATA[🚀 Zero-Allocation String Operations Substring creates new string. Array slicing copies memory. Span&#60;T&#62; provides zero-copy views. Massive performance gains. The Problem with Substring // ❌ Traditional: Allocates new strings string data = "2024-03-19T10:30:00"; string year = data.Substring(0, 4); // Allocates "2024" string month = data.Substring(5, 2); // Allocates "03" string day = data.Substring(8, 2); // [&#8230;]]]></description>
										<content:encoded><![CDATA[<div style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); color: white; padding: 50px 40px; border-radius: 16px; margin: 40px 0; box-shadow: 0 20px 60px rgba(0,0,0,0.3);">
<h2 style="margin: 0 0 20px 0; font-size: 2.8em; font-weight: 800; line-height: 1.2;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f680.png" alt="🚀" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Zero-Allocation String Operations</h2>
<p style="font-size: 1.4em; line-height: 1.8; margin: 0; opacity: 0.95;">Substring creates new string. Array slicing copies memory. <strong>Span&lt;T&gt;</strong> provides zero-copy views. Massive performance gains.</p>
</p></div>
<h3 style="color: #2c3e50; font-size: 2.2em; margin: 50px 0 30px 0; font-weight: 700; border-left: 5px solid #f5576c; padding-left: 20px;">The Problem with Substring</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
// <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Traditional: Allocates new strings
string data = "2024-03-19T10:30:00";
string year = data.Substring(0, 4);      // Allocates "2024"
string month = data.Substring(5, 2);     // Allocates "03"
string day = data.Substring(8, 2);       // Allocates "19"

// Process 1 million dates: 3 million allocations!
// Garbage collector works overtime

// <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Span: Zero allocations
ReadOnlySpan<char> data = "2024-03-19T10:30:00";
ReadOnlySpan<char> year = data.Slice(0, 4);   // No allocation
ReadOnlySpan<char> month = data.Slice(5, 2);  // No allocation
ReadOnlySpan<char> day = data.Slice(8, 2);    // No allocation

int yearNum = int.Parse(year);   // Parses directly from span
</pre>
<div style="background: #f8f9fa; padding: 40px; border-radius: 12px; margin: 40px 0; border: 2px solid #f093fb;">
<h4 style="color: #f5576c; margin-top: 0; font-size: 1.7em; font-weight: 700;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f3af.png" alt="🎯" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Span Basics</h4>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
// Stack-allocated array (no heap allocation!)
Span<int> numbers = stackalloc int[100];
numbers[0] = 42;

// View into existing array (no copy!)
int[] array = new int[100];
Span<int> slice = array.AsSpan(10, 50);  // Elements 10-59
slice[0] = 100;  // Modifies original array

// String as ReadOnlySpan (immutable)
ReadOnlySpan<char> text = "Hello, World!";
ReadOnlySpan<char> hello = text.Slice(0, 5);

// Can't do this (compile error):
// Span<char> span = "Hello";  // Strings are immutable
</pre>
</p></div>
<h3 style="color: #2c3e50; font-size: 2.2em; margin: 50px 0 30px 0; font-weight: 700; border-left: 5px solid #667eea; padding-left: 20px;">Real-World: CSV Parsing</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
// <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Traditional: Many allocations
public List<Person> ParseCSV(string csv)
{
    var people = new List<Person>();
    var lines = csv.Split('\n');  // Allocates array of strings
    
    foreach (var line in lines)
    {
        var parts = line.Split(',');  // Allocates array per line
        people.Add(new Person 
        { 
            Name = parts[0],  // Already allocated
            Age = int.Parse(parts[1]) 
        });
    }
    return people;
}

// <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Span: Minimal allocations
public List<Person> ParseCSVFast(ReadOnlySpan<char> csv)
{
    var people = new List<Person>();
    
    while (csv.Length > 0)
    {
        int newline = csv.IndexOf('\n');
        var line = newline >= 0 ? csv.Slice(0, newline) : csv;
        csv = newline >= 0 ? csv.Slice(newline + 1) : default;
        
        int comma = line.IndexOf(',');
        var name = line.Slice(0, comma);
        var age = line.Slice(comma + 1);
        
        people.Add(new Person 
        { 
            Name = name.ToString(),  // Only allocation here
            Age = int.Parse(age) 
        });
    }
    return people;
}

// Benchmark: 10x faster, 90% less memory
</pre>
<h3 style="color: #2c3e50; font-size: 2.2em; margin: 50px 0 30px 0; font-weight: 700; border-left: 5px solid #f39c12; padding-left: 20px;">stackalloc for Temp Buffers</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
// <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Allocates array on heap
byte[] buffer = new byte[256];
ReadData(buffer);

// <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Stack-allocated (no GC pressure)
Span<byte> buffer = stackalloc byte[256];
ReadData(buffer);

// Warning: Don't stackalloc large arrays!
// Stack is limited (typically 1MB)
// Use for small buffers only (< 1KB)

// Safe pattern
Span<byte> buffer = size <= 1024 
    ? stackalloc byte[size] 
    : new byte[size];
</pre>
<div style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); color: white; padding: 35px; border-radius: 12px; margin: 40px 0;">
<h4 style="margin-top: 0; font-size: 1.7em; font-weight: 700;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f527.png" alt="🔧" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Memory&lt;T&gt; for Async</h4>
<pre style="background: rgba(0,0,0,0.3); color: #fff; padding: 25px; border-radius: 8px; font-size: 1.05em; line-height: 1.8;">
// Span can't be used in async methods (stack-based)
// Use Memory<T> instead

public async Task ProcessAsync(Memory<byte> data)
{
    // Can hold across await
    await Task.Delay(100);
    
    // Convert to Span when needed
    Span<byte> span = data.Span;
    span[0] = 42;
}

// ReadOnlyMemory for immutable
public async Task<int> CountAsync(ReadOnlyMemory<char> text)
{
    await Task.Delay(100);
    return text.Span.Count('a');
}
</pre>
</p></div>
<div style="background: linear-gradient(135deg, #d4edda 0%, #c3e6cb 100%); padding: 35px; border-radius: 12px; margin: 40px 0; border-left: 5px solid #28a745;">
<h4 style="color: #155724; margin-top: 0; font-size: 1.7em; font-weight: 700;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> When to Use Span</h4>
<ul style="color: #155724; font-size: 1.15em; line-height: 2.2; margin: 20px 0;">
<li><strong>String parsing:</strong> CSV, JSON, log files</li>
<li><strong>Binary protocols:</strong> Network packets, file formats</li>
<li><strong>Hot paths:</strong> Performance-critical loops</li>
<li><strong>Large data processing:</strong> Avoid allocations</li>
<li><strong>Temporary buffers:</strong> stackalloc for small sizes</li>
</ul></div>
<div style="background: linear-gradient(135deg, #fff3cd 0%, #ffe69c 100%); border-left: 5px solid #ffc107; padding: 35px; margin: 50px 0; border-radius: 12px;">
<h4 style="color: #856404; margin-top: 0; font-size: 1.7em; font-weight: 700;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/26a0.png" alt="⚠" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Limitations</h4>
<ul style="color: #856404; font-size: 1.15em; line-height: 2.2; margin: 20px 0;">
<li><strong>Can't store in class fields:</strong> Span is stack-only (ref struct)</li>
<li><strong>Can't use in async:</strong> Use Memory&lt;T&gt; instead</li>
<li><strong>Can't box:</strong> No object, IEnumerable, etc.</li>
<li><strong>Learning curve:</strong> Different mental model</li>
</ul></div>
<blockquote style="background: linear-gradient(to right, #fce4ec, #f8bbd0); border-left: 6px solid #e91e63; padding: 40px; margin: 50px 0; border-radius: 12px;">
<p style="font-size: 1.5em; line-height: 1.9; margin: 0; color: #880e4f; font-style: italic; font-weight: 500;">"Log parser was allocating 500MB/second. Rewrote with Span&lt;char&gt;. Allocations down to 5MB/second. GC pauses gone. Throughput tripled. Span is game-changing for high-performance .NET."</p>
<footer style="margin-top: 20px; color: #ad1457; font-size: 1.15em; font-weight: 600;">— Performance Engineer</footer>
</blockquote>
]]></content:encoded>
					
					<wfw:commentRss>http://blog.ercanopak.com/c-use-span-for-high-performance-memory-operations/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>C#: Async/Await Best Practices &#8211; Avoid Common Mistakes</title>
		<link>http://blog.ercanopak.com/c-async-await-best-practices-avoid-common-mistakes/</link>
					<comments>http://blog.ercanopak.com/c-async-await-best-practices-avoid-common-mistakes/#respond</comments>
		
		<dc:creator><![CDATA[ErcanOPAK]]></dc:creator>
		<pubDate>Sun, 22 Mar 2026 09:05:42 +0000</pubDate>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Async Await]]></category>
		<category><![CDATA[Asynchronous Programming]]></category>
		<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[C# Tips]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[configureawait]]></category>
		<category><![CDATA[deadlock]]></category>
		<guid isPermaLink="false">http://blog.ercanopak.com/c-async-await-best-practices-avoid-common-mistakes/</guid>

					<description><![CDATA[⚡ Async Done Right Async/await is powerful but tricky. Common mistakes cause deadlocks, performance issues, bugs. Learn to do it right. ❌ Mistake 1: Async Void // ❌ BAD: Async void (only for event handlers!) public async void ProcessData() { await DoWorkAsync(); } // Problems: // - Can't await it // - Exceptions crash app [&#8230;]]]></description>
										<content:encoded><![CDATA[<div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 50px 40px; border-radius: 16px; margin: 40px 0; box-shadow: 0 20px 60px rgba(0,0,0,0.3);">
<h2 style="margin: 0 0 20px 0; font-size: 2.8em; font-weight: 800; line-height: 1.2;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/26a1.png" alt="⚡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Async Done Right</h2>
<p style="font-size: 1.4em; line-height: 1.8; margin: 0; opacity: 0.95;">Async/await is powerful but tricky. <strong>Common mistakes</strong> cause deadlocks, performance issues, bugs. Learn to do it right.</p>
</p></div>
<h3 style="color: #2c3e50; font-size: 2.2em; margin: 50px 0 30px 0; font-weight: 700; border-left: 5px solid #764ba2; padding-left: 20px;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Mistake 1: Async Void</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
// <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" /> BAD: Async void (only for event handlers!)
public async void ProcessData()
{
    await DoWorkAsync();
}
// Problems:
// - Can't await it
// - Exceptions crash app
// - No way to know when it completes

// <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> GOOD: Async Task
public async Task ProcessDataAsync()
{
    await DoWorkAsync();
}
// Can await, catch exceptions, compose operations

// Exception: Event handlers MUST be async void
private async void Button_Click(object sender, EventArgs e)
{
    try
    {
        await ProcessDataAsync();
    }
    catch (Exception ex)
    {
        // Handle exception - can't let it bubble up
        Logger.LogError(ex);
    }
}
</pre>
<h3 style="color: #2c3e50; font-size: 2.2em; margin: 50px 0 30px 0; font-weight: 700; border-left: 5px solid #f5576c; padding-left: 20px;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Mistake 2: Blocking on Async (Deadlock)</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
// <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" /> BAD: Deadlock in UI or ASP.NET (pre-Core)
public void ProcessData()
{
    var result = GetDataAsync().Result;  // DEADLOCK!
    // Or
    GetDataAsync().Wait();  // DEADLOCK!
}

async Task<string> GetDataAsync()
{
    await Task.Delay(1000);
    return "data";
}

// Why deadlock?
// 1. .Result blocks current thread
// 2. await tries to resume on same thread
// 3. Thread is blocked waiting for await
// 4. Deadlock!

// <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> GOOD: Async all the way
public async Task ProcessDataAsync()
{
    var result = await GetDataAsync();
}

// Or in console app / ASP.NET Core (no sync context)
public void Main()
{
    var result = GetDataAsync().GetAwaiter().GetResult();  // OK in console
}
</pre>
<div style="background: #f8f9fa; padding: 40px; border-radius: 12px; margin: 40px 0; border: 2px solid #667eea;">
<h4 style="color: #667eea; margin-top: 0; font-size: 1.7em; font-weight: 700;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Mistake 3: Not Using ConfigureAwait(false)</h4>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
// <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" /> In library code: Captures context unnecessarily
public async Task<Data> GetDataAsync()
{
    await httpClient.GetAsync(url);  // Resumes on original context
    return data;
}

// <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> GOOD: Library code should use ConfigureAwait(false)
public async Task<Data> GetDataAsync()
{
    await httpClient.GetAsync(url).ConfigureAwait(false);
    return data;
}

// Rule of thumb:
// - UI code: Don't use ConfigureAwait (need UI thread)
// - Library code: Always ConfigureAwait(false) (performance)
// - ASP.NET Core: Doesn't matter (no sync context)
</pre>
</p></div>
<h3 style="color: #2c3e50; font-size: 2.2em; margin: 50px 0 30px 0; font-weight: 700; border-left: 5px solid #f39c12; padding-left: 20px;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Mistake 4: Fire and Forget</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
// <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" /> BAD: Exceptions swallowed
public void DoWork()
{
    _ = ProcessDataAsync();  // Fire and forget - exception lost!
}

// <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> GOOD: Await or explicitly handle
public async Task DoWorkAsync()
{
    await ProcessDataAsync();
}

// Or if truly fire-and-forget, handle exceptions
public void DoWork()
{
    _ = ProcessDataSafelyAsync();
}

private async Task ProcessDataSafelyAsync()
{
    try
    {
        await ProcessDataAsync();
    }
    catch (Exception ex)
    {
        Logger.LogError(ex);
    }
}
</pre>
<h3 style="color: #2c3e50; font-size: 2.2em; margin: 50px 0 30px 0; font-weight: 700; border-left: 5px solid #00f2fe; padding-left: 20px;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Parallel Async Operations</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
// <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" /> BAD: Sequential (6 seconds total)
var user = await GetUserAsync();      // 2 seconds
var orders = await GetOrdersAsync();  // 2 seconds
var products = await GetProductsAsync();  // 2 seconds

// <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> GOOD: Parallel (2 seconds total)
var userTask = GetUserAsync();
var ordersTask = GetOrdersAsync();
var productsTask = GetProductsAsync();

await Task.WhenAll(userTask, ordersTask, productsTask);

var user = await userTask;
var orders = await ordersTask;
var products = await productsTask;

// Or even better
var (user, orders, products) = await (
    GetUserAsync(),
    GetOrdersAsync(),
    GetProductsAsync()
);
</pre>
<div style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); color: white; padding: 35px; border-radius: 12px; margin: 40px 0;">
<h4 style="margin-top: 0; font-size: 1.7em; font-weight: 700;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Cancellation Tokens</h4>
<pre style="background: rgba(0,0,0,0.3); color: #fff; padding: 25px; border-radius: 8px; font-size: 1.05em; line-height: 1.8;">
// Always accept CancellationToken
public async Task<Data> GetDataAsync(CancellationToken ct = default)
{
    // Pass to async operations
    var response = await httpClient.GetAsync(url, ct);
    
    // Check periodically in loops
    foreach (var item in items)
    {
        ct.ThrowIfCancellationRequested();
        await ProcessAsync(item, ct);
    }
    
    return data;
}

// Usage with timeout
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));
var data = await GetDataAsync(cts.Token);
</pre>
</p></div>
<div style="background: linear-gradient(135deg, #d4edda 0%, #c3e6cb 100%); padding: 35px; border-radius: 12px; margin: 40px 0; border-left: 5px solid #28a745;">
<h4 style="color: #155724; margin-top: 0; font-size: 1.7em; font-weight: 700;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Golden Rules</h4>
<ul style="color: #155724; font-size: 1.15em; line-height: 2.2; margin: 20px 0;">
<li><strong>Async all the way:</strong> Don&#8217;t block on async code</li>
<li><strong>Return Task, not void:</strong> Except event handlers</li>
<li><strong>Use ConfigureAwait(false):</strong> In library code</li>
<li><strong>Accept CancellationToken:</strong> For all async methods</li>
<li><strong>Parallel when independent:</strong> Use Task.WhenAll</li>
<li><strong>Suffix with Async:</strong> Name methods FooAsync</li>
</ul></div>
<div style="background: linear-gradient(135deg, #fff3cd 0%, #ffe69c 100%); border-left: 5px solid #ffc107; padding: 35px; margin: 50px 0; border-radius: 12px;">
<h4 style="color: #856404; margin-top: 0; font-size: 1.7em; font-weight: 700;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/26a0.png" alt="⚠" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Common Traps</h4>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
// <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Capturing loop variable
foreach (var item in items)
{
    tasks.Add(Task.Run(() => Process(item)));  // Captures 'item'!
}

// <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Copy to local variable
foreach (var item in items)
{
    var local = item;
    tasks.Add(Task.Run(() => Process(local)));
}

// <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Async lambda in LINQ (doesn't await!)
items.Select(async item => await ProcessAsync(item));

// <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Use Task.WhenAll
var tasks = items.Select(item => ProcessAsync(item));
await Task.WhenAll(tasks);
</pre>
</p></div>
<blockquote style="background: linear-gradient(to right, #e8eaf6, #c5cae9); border-left: 6px solid #5c6bc0; padding: 40px; margin: 50px 0; border-radius: 12px;">
<p style="font-size: 1.5em; line-height: 1.9; margin: 0; color: #1a237e; font-style: italic; font-weight: 500;">&#8220;App froze randomly. Found .Result blocking async code. Changed to async all the way. No more freezes. Then made parallel calls with Task.WhenAll. API response time: 5s → 1s. Async is powerful when done right.&#8221;</p>
<footer style="margin-top: 20px; color: #283593; font-size: 1.15em; font-weight: 600;">— C# Architect</footer>
</blockquote>
]]></content:encoded>
					
					<wfw:commentRss>http://blog.ercanopak.com/c-async-await-best-practices-avoid-common-mistakes/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>C#: Use LINQ Efficiently &#8211; Avoid Common Performance Pitfalls</title>
		<link>http://blog.ercanopak.com/c-use-linq-efficiently-avoid-common-performance-pitfalls/</link>
					<comments>http://blog.ercanopak.com/c-use-linq-efficiently-avoid-common-performance-pitfalls/#respond</comments>
		
		<dc:creator><![CDATA[ErcanOPAK]]></dc:creator>
		<pubDate>Sun, 22 Mar 2026 09:05:35 +0000</pubDate>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[C# Tips]]></category>
		<category><![CDATA[Database Performance]]></category>
		<category><![CDATA[EF Core]]></category>
		<category><![CDATA[entity framework]]></category>
		<category><![CDATA[linq]]></category>
		<category><![CDATA[LINQ Performance]]></category>
		<category><![CDATA[Query Optimization]]></category>
		<guid isPermaLink="false">http://blog.ercanopak.com/c-use-linq-efficiently-avoid-common-performance-pitfalls/</guid>

					<description><![CDATA[⚡ LINQ Done Right LINQ is powerful but easy to misuse. Common mistakes make queries 100x slower. Learn to write fast LINQ. ❌ Mistake 1: Multiple Enumerations // ❌ BAD: Query executed 3 times! var query = users.Where(u => u.Age > 18); // Not executed yet (deferred) var count = query.Count(); // Executes query var [&#8230;]]]></description>
										<content:encoded><![CDATA[<div style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); color: white; padding: 50px 40px; border-radius: 16px; margin: 40px 0; box-shadow: 0 20px 60px rgba(0,0,0,0.3);">
<h2 style="margin: 0 0 20px 0; font-size: 2.8em; font-weight: 800; line-height: 1.2;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/26a1.png" alt="⚡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> LINQ Done Right</h2>
<p style="font-size: 1.4em; line-height: 1.8; margin: 0; opacity: 0.95;">LINQ is powerful but easy to misuse. <strong>Common mistakes</strong> make queries 100x slower. Learn to write fast LINQ.</p>
</p></div>
<h3 style="color: #2c3e50; font-size: 2.2em; margin: 50px 0 30px 0; font-weight: 700; border-left: 5px solid #00f2fe; padding-left: 20px;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Mistake 1: Multiple Enumerations</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
// <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" /> BAD: Query executed 3 times!
var query = users.Where(u => u.Age > 18);  // Not executed yet (deferred)

var count = query.Count();      // Executes query
var first = query.First();      // Executes query again
var list = query.ToList();      // Executes query again!

// If users is IQueryable (EF Core), 3 database queries!

// <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> GOOD: Materialize once
var activeUsers = users.Where(u => u.Age > 18).ToList();

var count = activeUsers.Count;  // In-memory
var first = activeUsers.First();  // In-memory
</pre>
<h3 style="color: #2c3e50; font-size: 2.2em; margin: 50px 0 30px 0; font-weight: 700; border-left: 5px solid #f5576c; padding-left: 20px;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Mistake 2: Count() vs Any()</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
// <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" /> BAD: Counts all items just to check if > 0
if (users.Count() > 0)
{
    // Process
}

// <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> GOOD: Stops at first item
if (users.Any())
{
    // Process
}

// Database query comparison:
// Count(): SELECT COUNT(*) FROM Users  (scans entire table)
// Any(): SELECT TOP 1 FROM Users       (stops after 1 row)
</pre>
<div style="background: #f8f9fa; padding: 40px; border-radius: 12px; margin: 40px 0; border: 2px solid #4facfe;">
<h4 style="color: #00f2fe; margin-top: 0; font-size: 1.7em; font-weight: 700;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Mistake 3: Where + First vs FirstOrDefault</h4>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
// <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" /> BAD: Two operations
var user = users.Where(u => u.Id == 123).FirstOrDefault();

// <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> GOOD: Single operation with predicate
var user = users.FirstOrDefault(u => u.Id == 123);

// Database query:
// Where + First: Generates complex query
// FirstOrDefault(predicate): SELECT TOP 1 ... WHERE Id = 123
</pre>
</p></div>
<h3 style="color: #2c3e50; font-size: 2.2em; margin: 50px 0 30px 0; font-weight: 700; border-left: 5px solid #667eea; padding-left: 20px;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Mistake 4: Calling ToList() Too Early</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
// <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" /> BAD: Loads all users into memory, then filters
var activeUsers = context.Users
    .ToList()  // Loads ALL users from database
    .Where(u => u.IsActive)
    .Take(10);

// <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> GOOD: Filter in database, load only needed
var activeUsers = context.Users
    .Where(u => u.IsActive)
    .Take(10)
    .ToList();  // Only loads 10 users

// Database query:
// Bad: SELECT * FROM Users (gets 1M rows)
// Good: SELECT TOP 10 * FROM Users WHERE IsActive = 1
</pre>
<h3 style="color: #2c3e50; font-size: 2.2em; margin: 50px 0 30px 0; font-weight: 700; border-left: 5px solid #f39c12; padding-left: 20px;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Mistake 5: String Operations in Queries</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
// <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" /> BAD: Can't translate to SQL, loads all users
var users = context.Users
    .Where(u => u.Name.ToUpper() == searchTerm.ToUpper())
    .ToList();

// <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> GOOD: Use Contains for case-insensitive search
var users = context.Users
    .Where(u => EF.Functions.Like(u.Name, $"%{searchTerm}%"))
    .ToList();

// Or for exact match (case-insensitive)
var users = context.Users
    .Where(u => u.Name.ToLower() == searchTerm.ToLower())
    .ToList();
</pre>
<div style="background: linear-gradient(135deg, #fa709a 0%, #fee140 100%); color: white; padding: 35px; border-radius: 12px; margin: 40px 0;">
<h4 style="margin-top: 0; font-size: 1.7em; font-weight: 700;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Mistake 6: N+1 Query Problem</h4>
<pre style="background: rgba(0,0,0,0.3); color: #fff; padding: 25px; border-radius: 8px; font-size: 1.05em; line-height: 1.8;">
// <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" /> BAD: 1 query for users + N queries for orders
var users = context.Users.ToList();
foreach (var user in users)  // 100 users
{
    var orders = context.Orders
        .Where(o => o.UserId == user.Id)
        .ToList();  // Query executed 100 times!
}
// Total: 101 database queries

// <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> GOOD: Use Include (eager loading)
var users = context.Users
    .Include(u => u.Orders)
    .ToList();
// Total: 1 database query with JOIN
</pre>
</p></div>
<h3 style="color: #2c3e50; font-size: 2.2em; margin: 50px 0 30px 0; font-weight: 700; border-left: 5px solid #27ae60; padding-left: 20px;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Best Practices</h3>
<div style="background: linear-gradient(135deg, #d4edda 0%, #c3e6cb 100%); padding: 35px; border-radius: 12px; margin: 40px 0; border-left: 5px solid #28a745;">
<h4 style="color: #155724; margin-top: 0; font-size: 1.7em; font-weight: 700;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Golden Rules</h4>
<ul style="color: #155724; font-size: 1.15em; line-height: 2.2; margin: 20px 0;">
<li><strong>Filter first, materialize last:</strong> Where → Select → ToList()</li>
<li><strong>Use Any() for existence:</strong> Not Count() > 0</li>
<li><strong>Use FirstOrDefault(predicate):</strong> Not Where().First()</li>
<li><strong>Include related data:</strong> Avoid N+1 queries</li>
<li><strong>Project early:</strong> Select only needed columns</li>
<li><strong>AsNoTracking for read-only:</strong> Faster queries in EF Core</li>
</ul></div>
<h3 style="color: #2c3e50; font-size: 2.2em; margin: 50px 0 30px 0; font-weight: 700; border-left: 5px solid #667eea; padding-left: 20px;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Optimized Query Example</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
// <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> BEST: All optimizations applied
var recentOrders = context.Orders
    .AsNoTracking()  // Read-only, faster
    .Where(o => o.CreatedAt > DateTime.Now.AddDays(-30))  // Filter in DB
    .Include(o => o.User)  // Eager load related data
    .Select(o => new OrderDto  // Project to DTO
    {
        Id = o.Id,
        UserName = o.User.Name,
        Total = o.Total,
        Date = o.CreatedAt
    })
    .Take(100)  // Limit results
    .ToList();  // Materialize once

// Single efficient database query
// No N+1 problem
// Only needed columns selected
// No change tracking overhead
</pre>
<div style="background: linear-gradient(135deg, #fff3cd 0%, #ffe69c 100%); border-left: 5px solid #ffc107; padding: 35px; margin: 50px 0; border-radius: 12px;">
<h4 style="color: #856404; margin-top: 0; font-size: 1.7em; font-weight: 700;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f50d.png" alt="🔍" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Debug LINQ</h4>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
// See generated SQL (EF Core)
var query = context.Users.Where(u => u.IsActive);
var sql = query.ToQueryString();
Console.WriteLine(sql);

// Log all queries
// appsettings.json
{
  "Logging": {
    "LogLevel": {
      "Microsoft.EntityFrameworkCore.Database.Command": "Information"
    }
  }
}
</pre>
</p></div>
<blockquote style="background: linear-gradient(to right, #e0f7fa, #b2ebf2); border-left: 6px solid #00bcd4; padding: 40px; margin: 50px 0; border-radius: 12px;">
<p style="font-size: 1.5em; line-height: 1.9; margin: 0; color: #006064; font-style: italic; font-weight: 500;">&#8220;Dashboard was loading in 8 seconds. Found Count() instead of Any(), N+1 queries, early ToList(). Fixed all LINQ mistakes. Now loads in 0.3 seconds. 27x faster with zero infrastructure changes.&#8221;</p>
<footer style="margin-top: 20px; color: #00838f; font-size: 1.15em; font-weight: 600;">— .NET Performance Engineer</footer>
</blockquote>
]]></content:encoded>
					
					<wfw:commentRss>http://blog.ercanopak.com/c-use-linq-efficiently-avoid-common-performance-pitfalls/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>C#: Use Pattern Matching for Cleaner Type Checks and Switches</title>
		<link>http://blog.ercanopak.com/c-use-pattern-matching-for-cleaner-type-checks-and-switches/</link>
					<comments>http://blog.ercanopak.com/c-use-pattern-matching-for-cleaner-type-checks-and-switches/#respond</comments>
		
		<dc:creator><![CDATA[ErcanOPAK]]></dc:creator>
		<pubDate>Sun, 22 Mar 2026 09:05:28 +0000</pubDate>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[C# 10]]></category>
		<category><![CDATA[C# 11]]></category>
		<category><![CDATA[C# 9]]></category>
		<category><![CDATA[Clean Code]]></category>
		<category><![CDATA[Language Features]]></category>
		<category><![CDATA[Modern C#]]></category>
		<category><![CDATA[Pattern Matching]]></category>
		<category><![CDATA[Switch Expressions]]></category>
		<category><![CDATA[Type Patterns]]></category>
		<guid isPermaLink="false">http://blog.ercanopak.com/c-use-pattern-matching-for-cleaner-type-checks-and-switches/</guid>

					<description><![CDATA[🎯 Switch on Steroids Type casting everywhere? Nested if-else chains? Pattern matching makes type checks and complex conditions elegant. Type Pattern (is) // ❌ Old way: Type check + cast if (obj is string) { string s = (string)obj; Console.WriteLine(s.ToUpper()); } // ✅ Pattern matching: Check and declare in one if (obj is string s) [&#8230;]]]></description>
										<content:encoded><![CDATA[<div style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); color: white; padding: 50px 40px; border-radius: 16px; margin: 40px 0; box-shadow: 0 20px 60px rgba(0,0,0,0.3);">
<h2 style="margin: 0 0 20px 0; font-size: 2.8em; font-weight: 800; line-height: 1.2;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f3af.png" alt="🎯" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Switch on Steroids</h2>
<p style="font-size: 1.4em; line-height: 1.8; margin: 0; opacity: 0.95;">Type casting everywhere? Nested if-else chains? <strong>Pattern matching</strong> makes type checks and complex conditions elegant.</p>
</p></div>
<h3 style="color: #2c3e50; font-size: 2.2em; margin: 50px 0 30px 0; font-weight: 700; border-left: 5px solid #f5576c; padding-left: 20px;">Type Pattern (is)</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
// <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Old way: Type check + cast
if (obj is string)
{
    string s = (string)obj;
    Console.WriteLine(s.ToUpper());
}

// <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Pattern matching: Check and declare in one
if (obj is string s)
{
    Console.WriteLine(s.ToUpper());
}

// Works with null check too
if (obj is not null)
{
    // obj is definitely not null here
}
</pre>
<h3 style="color: #2c3e50; font-size: 2.2em; margin: 50px 0 30px 0; font-weight: 700; border-left: 5px solid #667eea; padding-left: 20px;">Switch Expressions</h3>
<div style="background: #f8f9fa; padding: 40px; border-radius: 12px; margin: 40px 0; border: 2px solid #f093fb;">
<h4 style="color: #f5576c; margin-top: 0; font-size: 1.7em; font-weight: 700;">Before (Old Switch)</h4>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
string GetDiscount(Customer customer)
{
    switch (customer.Type)
    {
        case CustomerType.Regular:
            return "5%";
        case CustomerType.Premium:
            return "10%";
        case CustomerType.VIP:
            return "20%";
        default:
            return "0%";
    }
}
</pre>
<h4 style="color: #27ae60; margin-top: 30px; font-size: 1.7em; font-weight: 700;">After (Switch Expression)</h4>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
string GetDiscount(Customer customer) => customer.Type switch
{
    CustomerType.Regular => "5%",
    CustomerType.Premium => "10%",
    CustomerType.VIP => "20%",
    _ => "0%"
};

// Concise, expression-based, returns value directly
</pre>
</p></div>
<h3 style="color: #2c3e50; font-size: 2.2em; margin: 50px 0 30px 0; font-weight: 700; border-left: 5px solid #f39c12; padding-left: 20px;">Property Patterns</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
decimal CalculateShipping(Order order) => order switch
{
    // Match on properties
    { Total: > 100 } => 0,                    // Free shipping
    { Country: "US", Total: > 50 } => 5,      // US discount
    { Country: "US" } => 10,                  // US standard
    { IsPriority: true } => 25,               // Priority
    _ => 15                                   // Default
};

// Nested property patterns
string GetRisk(User user) => user switch
{
    { Age: < 18 } => "Minor",
    { Orders: { Count: > 100 }, AccountAge: > 365 } => "Trusted",
    { Orders: { Count: 0 }, AccountAge: < 7 } => "New",
    _ => "Regular"
};
</pre>
<h3 style="color: #2c3e50; font-size: 2.2em; margin: 50px 0 30px 0; font-weight: 700; border-left: 5px solid #00f2fe; padding-left: 20px;">Relational Patterns</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
string GetTemperatureDescription(int temp) => temp switch
{
    < 0 => "Freezing",
    >= 0 and < 10 => "Cold",
    >= 10 and < 20 => "Cool",
    >= 20 and < 30 => "Warm",
    >= 30 => "Hot"
};

// Or patterns
bool IsWeekend(DayOfWeek day) => day is DayOfWeek.Saturday or DayOfWeek.Sunday;

// Not pattern
bool IsWeekday(DayOfWeek day) => day is not (DayOfWeek.Saturday or DayOfWeek.Sunday);
</pre>
<h3 style="color: #2c3e50; font-size: 2.2em; margin: 50px 0 30px 0; font-weight: 700; border-left: 5px solid #667eea; padding-left: 20px;">Type Patterns in Switch</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
string Describe(object obj) => obj switch
{
    int i => $"Integer: {i}",
    string s => $"String: {s}",
    DateTime dt => $"Date: {dt:yyyy-MM-dd}",
    int[] arr => $"Array with {arr.Length} elements",
    null => "Null",
    _ => "Unknown type"
};

// With property patterns
decimal CalculateArea(Shape shape) => shape switch
{
    Circle { Radius: var r } => Math.PI * r * r,
    Rectangle { Width: var w, Height: var h } => w * h,
    Square { Side: var s } => s * s,
    _ => 0
};
</pre>
<div style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); color: white; padding: 35px; border-radius: 12px; margin: 40px 0;">
<h4 style="margin-top: 0; font-size: 1.7em; font-weight: 700;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f3a8.png" alt="🎨" class="wp-smiley" style="height: 1em; max-height: 1em;" /> List Patterns (C# 11)</h4>
<pre style="background: rgba(0,0,0,0.3); color: #fff; padding: 25px; border-radius: 8px; font-size: 1.05em; line-height: 1.8;">
string Analyze(int[] numbers) => numbers switch
{
    [] => "Empty",
    [var single] => $"Single: {single}",
    [var first, var second] => $"Pair: {first}, {second}",
    [var first, .., var last] => $"Multiple: {first}...{last}",
    [1, 2, 3] => "Exactly 1, 2, 3",
    [var x, > 10, ..] => $"Starts with {x}, second > 10"
};

// Example usage
Analyze(new[] { 5 });           // "Single: 5"
Analyze(new[] { 1, 2 });        // "Pair: 1, 2"
Analyze(new[] { 1, 2, 3, 4 });  // "Multiple: 1...4"
</pre>
</p></div>
<div style="background: linear-gradient(135deg, #d4edda 0%, #c3e6cb 100%); padding: 35px; border-radius: 12px; margin: 40px 0; border-left: 5px solid #28a745;">
<h4 style="color: #155724; margin-top: 0; font-size: 1.7em; font-weight: 700;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Benefits</h4>
<ul style="color: #155724; font-size: 1.15em; line-height: 2.2; margin: 20px 0;">
<li><strong>Less code:</strong> No explicit casts or temp variables</li>
<li><strong>More readable:</strong> Intent is clear</li>
<li><strong>Type safe:</strong> Compiler checks exhaustiveness</li>
<li><strong>Expression-based:</strong> Can use in LINQ, assignments</li>
<li><strong>Performance:</strong> Same or better than if-else chains</li>
</ul></div>
<div style="background: linear-gradient(135deg, #fff3cd 0%, #ffe69c 100%); border-left: 5px solid #ffc107; padding: 35px; margin: 50px 0; border-radius: 12px;">
<h4 style="color: #856404; margin-top: 0; font-size: 1.7em; font-weight: 700;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Real-World Example</h4>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
// HTTP status code handling
string GetMessage(int statusCode) => statusCode switch
{
    200 => "OK",
    >= 200 and < 300 => "Success",
    404 => "Not Found",
    >= 400 and < 500 => "Client Error",
    >= 500 => "Server Error",
    _ => "Unknown"
};

// Validation with patterns
bool IsValidEmail(string? email) => email switch
{
    null or "" => false,
    { Length: > 100 } => false,
    var e when e.Contains('@') && e.Contains('.') => true,
    _ => false
};
</pre>
</p></div>
<blockquote style="background: linear-gradient(to right, #fce4ec, #f8bbd0); border-left: 6px solid #e91e63; padding: 40px; margin: 50px 0; border-radius: 12px;">
<p style="font-size: 1.5em; line-height: 1.9; margin: 0; color: #880e4f; font-style: italic; font-weight: 500;">&#8220;Refactored payment processor with pattern matching. 200 lines of if-else became 50 lines of switch expressions. Logic clear at a glance. New payment types? Add one line. Code reviews take 5 minutes now.&#8221;</p>
<footer style="margin-top: 20px; color: #ad1457; font-size: 1.15em; font-weight: 600;">— Senior C# Developer</footer>
</blockquote>
]]></content:encoded>
					
					<wfw:commentRss>http://blog.ercanopak.com/c-use-pattern-matching-for-cleaner-type-checks-and-switches/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>C#: Use Index and Range for Clean Array Slicing</title>
		<link>http://blog.ercanopak.com/c-use-index-and-range-for-clean-array-slicing/</link>
					<comments>http://blog.ercanopak.com/c-use-index-and-range-for-clean-array-slicing/#respond</comments>
		
		<dc:creator><![CDATA[ErcanOPAK]]></dc:creator>
		<pubDate>Thu, 19 Mar 2026 20:29:53 +0000</pubDate>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Array Slicing]]></category>
		<category><![CDATA[C# 8]]></category>
		<category><![CDATA[C# Tips]]></category>
		<category><![CDATA[Clean Code]]></category>
		<category><![CDATA[collections]]></category>
		<category><![CDATA[Index and Range]]></category>
		<category><![CDATA[Modern C#]]></category>
		<category><![CDATA[Ranges]]></category>
		<category><![CDATA[Syntax Sugar]]></category>
		<guid isPermaLink="false">http://blog.ercanopak.com/c-use-index-and-range-for-clean-array-slicing/</guid>

					<description><![CDATA[🔪 Slice Arrays Like Python Array.Copy() for slicing? Verbose. Index (^) and Range (..) operators make it elegant. Index from End (^) var numbers = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // Old way: Last element var last = numbers[numbers.Length - 1]; // New way: ^1 means "1 [&#8230;]]]></description>
										<content:encoded><![CDATA[<div style="background: linear-gradient(135deg, #fa709a 0%, #fee140 100%); color: white; padding: 50px 40px; border-radius: 16px; margin: 40px 0; box-shadow: 0 20px 60px rgba(0,0,0,0.3);">
<h2 style="margin: 0 0 20px 0; font-size: 2.8em; font-weight: 800; line-height: 1.2;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f52a.png" alt="🔪" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Slice Arrays Like Python</h2>
<p style="font-size: 1.4em; line-height: 1.8; margin: 0; opacity: 0.95;">Array.Copy() for slicing? Verbose. <strong>Index (^) and Range (..)</strong> operators make it elegant.</p>
</p></div>
<h3 style="color: #2c3e50; font-size: 2.2em; margin: 50px 0 30px 0; font-weight: 700; border-left: 5px solid #fee140; padding-left: 20px;">Index from End (^)</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
var numbers = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

// Old way: Last element
var last = numbers[numbers.Length - 1];

// New way: ^1 means "1 from end"
var last = numbers[^1];  // 9

// Second from end
var secondLast = numbers[^2];  // 8

// Third from end
var third = numbers[^3];  // 7
</pre>
<h3 style="color: #2c3e50; font-size: 2.2em; margin: 50px 0 30px 0; font-weight: 700; border-left: 5px solid #fa709a; padding-left: 20px;">Range Slicing (..)</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
var numbers = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

// First 3 elements
var first3 = numbers[0..3];  // { 0, 1, 2 }

// Skip first 3, get rest
var rest = numbers[3..];  // { 3, 4, 5, 6, 7, 8, 9 }

// Last 3 elements
var last3 = numbers[^3..];  // { 7, 8, 9 }

// Everything except last 2
var allButLast2 = numbers[..^2];  // { 0, 1, 2, 3, 4, 5, 6, 7 }

// Middle elements (skip first 2 and last 2)
var middle = numbers[2..^2];  // { 2, 3, 4, 5, 6, 7 }

// All elements (copy)
var copy = numbers[..];
</pre>
<div style="background: #f8f9fa; padding: 40px; border-radius: 12px; margin: 40px 0; border: 2px solid #fa709a;">
<h4 style="color: #fa709a; margin-top: 0; font-size: 1.7em; font-weight: 700;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f3af.png" alt="🎯" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Real-World Examples</h4>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
// String slicing
string text = "Hello, World!";
var hello = text[..5];  // "Hello"
var world = text[7..^1];  // "World"

// List slicing
var items = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var firstHalf = items[..5];  // { 1, 2, 3, 4, 5 }

// Pagination
int page = 2;
int pageSize = 3;
var pageItems = items[(page * pageSize)..((page + 1) * pageSize)];

// Remove header and footer
var lines = File.ReadAllLines("data.txt");
var dataOnly = lines[1..^1];  // Skip first and last line
</pre>
</p></div>
<div style="background: linear-gradient(135deg, #d4edda 0%, #c3e6cb 100%); padding: 35px; border-radius: 12px; margin: 40px 0; border-left: 5px solid #28a745;">
<h4 style="color: #155724; margin-top: 0; font-size: 1.7em; font-weight: 700;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Cheat Sheet</h4>
<table style="width: 100%; border-collapse: collapse; margin: 20px 0;">
<tr style="background: #28a745; color: white;">
<th style="padding: 15px; text-align: left;">Syntax</th>
<th style="padding: 15px; text-align: left;">Meaning</th>
</tr>
<tr>
<td style="padding: 12px; border-bottom: 1px solid #ddd;"><code>^1</code></td>
<td style="padding: 12px; border-bottom: 1px solid #ddd;">Last element</td>
</tr>
<tr style="background: #f8f9fa;">
<td style="padding: 12px; border-bottom: 1px solid #ddd;"><code>^n</code></td>
<td style="padding: 12px; border-bottom: 1px solid #ddd;">n-th from end</td>
</tr>
<tr>
<td style="padding: 12px; border-bottom: 1px solid #ddd;"><code>[..3]</code></td>
<td style="padding: 12px; border-bottom: 1px solid #ddd;">First 3 elements</td>
</tr>
<tr style="background: #f8f9fa;">
<td style="padding: 12px; border-bottom: 1px solid #ddd;"><code>[3..]</code></td>
<td style="padding: 12px; border-bottom: 1px solid #ddd;">From index 3 to end</td>
</tr>
<tr>
<td style="padding: 12px; border-bottom: 1px solid #ddd;"><code>[^3..]</code></td>
<td style="padding: 12px; border-bottom: 1px solid #ddd;">Last 3 elements</td>
</tr>
<tr style="background: #f8f9fa;">
<td style="padding: 12px;"><code>[2..5]</code></td>
<td style="padding: 12px;">Elements 2, 3, 4</td>
</tr>
</table></div>
<blockquote style="background: linear-gradient(to right, #fff9e6, #ffecb3); border-left: 6px solid #ff9800; padding: 40px; margin: 50px 0; border-radius: 12px;">
<p style="font-size: 1.5em; line-height: 1.9; margin: 0; color: #e65100; font-style: italic; font-weight: 500;">&#8220;CSV parsing code was full of substring calculations. Switched to ranges. Code is 50% shorter, infinitely more readable. No more off-by-one errors.&#8221;</p>
<footer style="margin-top: 20px; color: #ef6c00; font-size: 1.15em; font-weight: 600;">— Data Engineer</footer>
</blockquote>
]]></content:encoded>
					
					<wfw:commentRss>http://blog.ercanopak.com/c-use-index-and-range-for-clean-array-slicing/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>C#: Use Expression-Bodied Members for One-Liners</title>
		<link>http://blog.ercanopak.com/c-use-expression-bodied-members-for-one-liners/</link>
					<comments>http://blog.ercanopak.com/c-use-expression-bodied-members-for-one-liners/#respond</comments>
		
		<dc:creator><![CDATA[ErcanOPAK]]></dc:creator>
		<pubDate>Thu, 19 Mar 2026 20:29:46 +0000</pubDate>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[C# 6]]></category>
		<category><![CDATA[C# Tips]]></category>
		<category><![CDATA[Clean Code]]></category>
		<category><![CDATA[Concise Code]]></category>
		<category><![CDATA[Expression Bodies]]></category>
		<category><![CDATA[Lambda Syntax]]></category>
		<category><![CDATA[Methods]]></category>
		<category><![CDATA[Modern C#]]></category>
		<category><![CDATA[Properties]]></category>
		<guid isPermaLink="false">http://blog.ercanopak.com/c-use-expression-bodied-members-for-one-liners/</guid>

					<description><![CDATA[✨ Write Less, Express More Simple properties and methods don&#8217;t need full syntax. Expression bodies (=>) make code concise. Before: Verbose Syntax public class User { public string FirstName { get; set; } public string LastName { get; set; } // Verbose property public string FullName { get { return $"{FirstName} {LastName}"; } } // [&#8230;]]]></description>
										<content:encoded><![CDATA[<div style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); color: white; padding: 50px 40px; border-radius: 16px; margin: 40px 0; box-shadow: 0 20px 60px rgba(0,0,0,0.3);">
<h2 style="margin: 0 0 20px 0; font-size: 2.8em; font-weight: 800; line-height: 1.2;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2728.png" alt="✨" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Write Less, Express More</h2>
<p style="font-size: 1.4em; line-height: 1.8; margin: 0; opacity: 0.95;">Simple properties and methods don&#8217;t need full syntax. <strong>Expression bodies</strong> (=>) make code concise.</p>
</p></div>
<h3 style="color: #2c3e50; font-size: 2.2em; margin: 50px 0 30px 0; font-weight: 700; border-left: 5px solid #00f2fe; padding-left: 20px;">Before: Verbose Syntax</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
public class User
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    
    // Verbose property
    public string FullName
    {
        get { return $"{FirstName} {LastName}"; }
    }
    
    // Verbose method
    public string GetGreeting()
    {
        return $"Hello, {FirstName}!";
    }
    
    // Verbose readonly property
    public bool IsValid
    {
        get { return !string.IsNullOrEmpty(FirstName); }
    }
}
</pre>
<h3 style="color: #2c3e50; font-size: 2.2em; margin: 50px 0 30px 0; font-weight: 700; border-left: 5px solid #27ae60; padding-left: 20px;">After: Expression Bodies</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
public class User
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    
    // Expression-bodied property
    public string FullName => $"{FirstName} {LastName}";
    
    // Expression-bodied method
    public string GetGreeting() => $"Hello, {FirstName}!";
    
    // Expression-bodied readonly property
    public bool IsValid => !string.IsNullOrEmpty(FirstName);
    
    // Works with getters and setters
    private string _email;
    public string Email
    {
        get => _email;
        set => _email = value?.ToLower();
    }
    
    // Constructors too!
    public User(string first, string last) => (FirstName, LastName) = (first, last);
}
</pre>
<div style="background: #f8f9fa; padding: 40px; border-radius: 12px; margin: 40px 0; border: 2px solid #4facfe;">
<h4 style="color: #00f2fe; margin-top: 0; font-size: 1.7em; font-weight: 700;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f3af.png" alt="🎯" class="wp-smiley" style="height: 1em; max-height: 1em;" /> All Supported Members</h4>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">
public class Example
{
    // Properties
    public string Name => "Example";
    
    // Methods
    public int Add(int a, int b) => a + b;
    
    // Operators
    public static Example operator +(Example a, Example b) => new Example();
    
    // Indexers
    public string this[int index] => items[index];
    
    // Finalizers
    ~Example() => Console.WriteLine("Destroyed");
    
    // Events (add/remove)
    private EventHandler _changed;
    public event EventHandler Changed
    {
        add => _changed += value;
        remove => _changed -= value;
    }
}
</pre>
</p></div>
<div style="background: linear-gradient(135deg, #fff3cd 0%, #ffe69c 100%); border-left: 5px solid #ffc107; padding: 35px; margin: 50px 0; border-radius: 12px;">
<h4 style="color: #856404; margin-top: 0; font-size: 1.7em; font-weight: 700;"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/26a1.png" alt="⚡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> When to Use</h4>
<ul style="color: #856404; font-size: 1.15em; line-height: 2.2; margin: 20px 0;">
<li><strong>Single expression:</strong> One return value, no complex logic</li>
<li><strong>Computed properties:</strong> Derived from other properties</li>
<li><strong>Simple methods:</strong> One-liners that return immediately</li>
<li><strong>Avoid for:</strong> Multiple statements, complex logic, debugging breakpoints needed</li>
</ul></div>
<blockquote style="background: linear-gradient(to right, #e0f7fa, #b2ebf2); border-left: 6px solid #00bcd4; padding: 40px; margin: 50px 0; border-radius: 12px;">
<p style="font-size: 1.5em; line-height: 1.9; margin: 0; color: #006064; font-style: italic; font-weight: 500;">&#8220;DTOs went from 200 lines to 80 lines. Same functionality. Expression bodies eliminated so much boilerplate. Code reviews focus on logic, not syntax.&#8221;</p>
<footer style="margin-top: 20px; color: #00838f; font-size: 1.15em; font-weight: 600;">— C# Architect</footer>
</blockquote>
]]></content:encoded>
					
					<wfw:commentRss>http://blog.ercanopak.com/c-use-expression-bodied-members-for-one-liners/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
