Skip to content

Bits of .NET

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

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

Author: ErcanOPAK

C#

C#: Use Init-Only Setters for Immutable Objects After Construction

- 30.03.26 - ErcanOPAK comment on C#: Use Init-Only Setters for Immutable Objects After Construction

πŸ”’ 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 […]

Read More
C#

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

- 30.03.26 - ErcanOPAK comment on C#: Use Expression-Bodied Members for Concise Single-Line Methods

➑️ 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, […]

Read More
C#

C#: Enable Nullable Reference Types to Eliminate Null Reference Exceptions

- 30.03.26 - ErcanOPAK comment on C#: Enable Nullable Reference Types to Eliminate Null Reference Exceptions

πŸ›‘οΈ No More NullReferenceException NullReferenceException killing your app? Can’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 […]

Read More
C#

C#: Use Record Types for Immutable Data Objects

- 30.03.26 - ErcanOPAK comment on C#: Use Record Types for Immutable Data Objects

πŸ“¦ 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 { […]

Read More
SQL

SQL: Use CTEs for Readable Complex Queries

- 30.03.26 - ErcanOPAK comment on SQL: Use CTEs for Readable Complex Queries

πŸ“ Named Subqueries Nested subqueries everywhere? Can’t understand your own query? CTEs (WITH clause) create temporary named result sets. Makes complex queries readable. The Subquery Nightmare — ❌ Nested subqueries – Unreadable! SELECT customer_name, total_orders, avg_order_value FROM ( SELECT c.name AS customer_name, COUNT(o.id) AS total_orders, AVG(o.total) AS avg_order_value FROM customers c JOIN ( SELECT * […]

Read More
SQL

SQL: Use Window Functions for Advanced Analytical Queries

- 30.03.26 - ErcanOPAK comment on SQL: Use Window Functions for Advanced Analytical Queries

πŸ“Š SQL Superpowers Need row numbers? Running totals? Rankings? Window functions perform calculations across table rows without GROUP BY. Game-changing for analytics. ROW_NUMBER() – Assign Row Numbers — ❌ Old way: Can’t number rows easily SELECT name, salary, department FROM employees ORDER BY salary DESC; — βœ… Window function: Add row numbers SELECT ROW_NUMBER() OVER […]

Read More
Asp.Net Core

.NET Core: Use Background Services for Long-Running Tasks

- 30.03.26 - ErcanOPAK comment on .NET Core: Use Background Services for Long-Running Tasks

⏰ Tasks That Run Forever Need to process queue every minute? Send emails in background? Background Services run continuously alongside your ASP.NET app. Perfect for scheduled tasks, workers. Create Background Service public class EmailProcessorService : BackgroundService { private readonly ILogger _logger; private readonly IServiceProvider _serviceProvider; public EmailProcessorService( ILogger logger, IServiceProvider serviceProvider) { _logger = logger; […]

Read More
Asp.Net Core

.NET Core: Use Minimal APIs for Lightweight HTTP Services

- 30.03.26 - ErcanOPAK comment on .NET Core: Use Minimal APIs for Lightweight HTTP Services

πŸš€ APIs in 10 Lines of Code MVC Controllers for simple API? Overkill. Minimal APIs (.NET 6+) create HTTP endpoints with minimal ceremony. Perfect for microservices, simple APIs. Traditional Controller vs Minimal API // ❌ Traditional Controller (verbose) [ApiController] [Route(“api/[controller]”)] public class UsersController : ControllerBase { private readonly IUserService _userService; public UsersController(IUserService userService) { _userService […]

Read More
Git

Git: Use Cherry-Pick to Apply Specific Commits Across Branches

- 30.03.26 - ErcanOPAK comment on Git: Use Cherry-Pick to Apply Specific Commits Across Branches

πŸ’ Pick Commits Like Cherries Need one commit from another branch? Don’t merge everything. Cherry-pick copies specific commits to your current branch. Surgical precision. The Problem # Scenario: Bug fix on wrong branch git branch * feature-login main hotfix # You committed bug fix to feature-login # But it needs to be on hotfix branch […]

Read More
Git

Git: Use Interactive Rebase to Clean Up Commit History Before Merge

- 30.03.26 - ErcanOPAK comment on Git: Use Interactive Rebase to Clean Up Commit History Before Merge

πŸ”§ Rewrite Git History 50 commits saying ‘fix typo’, ‘WIP’, ‘oops’? Messy history before PR? Interactive rebase lets you squash, reword, reorder commits. Clean history like a pro. The Messy History Problem git log –oneline a1b2c3d fix typo d4e5f6g WIP g7h8i9j oops forgot file j1k2l3m fix typo again m4n5o6p actually fix the bug p7q8r9s Add […]

Read More
Ajax

Ajax: Use Fetch API Instead of XMLHttpRequest for Clean Async Requests

- 30.03.26 - ErcanOPAK comment on Ajax: Use Fetch API Instead of XMLHttpRequest for Clean Async Requests

🌐 Modern Ajax Made Simple XMLHttpRequest? 10 lines for simple GET? Callback hell? Fetch API is promise-based, clean syntax, built-in JSON parsing. Modern Ajax the right way. The Old Way (XMLHttpRequest) // ❌ XMLHttpRequest – Verbose and ugly const xhr = new XMLHttpRequest(); xhr.open(‘GET’, ‘https://api.example.com/users’); xhr.onload = function() { if (xhr.status === 200) { const […]

Read More
JavaScript

JavaScript: Use Destructuring to Extract Values Cleanly

- 30.03.26 - ErcanOPAK comment on JavaScript: Use Destructuring to Extract Values Cleanly

πŸ“¦ Unpack Like Python Accessing nested properties? const x = obj.prop.nested? Verbose. Destructuring extracts values from objects and arrays elegantly. One line replaces five. Object Destructuring const user = { name: ‘Alice’, age: 30, email: ‘alice@example.com’, address: { city: ‘New York’, country: ‘USA’ } }; // ❌ Old way const name = user.name; const age […]

Read More
HTML

HTML: Use Semantic HTML5 Elements for Better SEO and Accessibility

- 30.03.26 - ErcanOPAK comment on HTML: Use Semantic HTML5 Elements for Better SEO and Accessibility

πŸ“ Meaningful HTML Markup Everything is a div? Search engines confused, screen readers lost. Semantic HTML5 uses elements that describe their purpose: <header>, <nav>, <article>, <section>. Better SEO, better accessibility. The Div Soup Problem Home About … Article Title … Β© 2024 Semantic HTML5 Solution Home About … Article Title Article content… Section Heading Section […]

Read More
CSS

CSS: Use Grid auto-fit and auto-fill for Responsive Layouts Without Media Queries

- 30.03.26 - ErcanOPAK comment on CSS: Use Grid auto-fit and auto-fill for Responsive Layouts Without Media Queries

πŸ“± Responsive Grids, Zero Media Queries Media queries for every breakpoint? Tedious. Grid auto-fit/auto-fill creates responsive layouts automatically. Items reflow based on space available. The Magic Formula .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 1rem; } /* That’s it! Fully responsive without media queries Items wrap automatically based on available space */ 🎯 […]

Read More
Windows

Windows 11: Use Virtual Desktops to Organize Workspaces

- 30.03.26 - ErcanOPAK comment on Windows 11: Use Virtual Desktops to Organize Workspaces

πŸ–₯️ Multiple Desktops, One PC 20 windows open? Can’t find anything? Virtual Desktops let you organize: Desktop 1 = Work, Desktop 2 = Personal, Desktop 3 = Development. Switch with keyboard shortcut. Quick Start # Open Task View Win + Tab # Create new desktop Click “+ New Desktop” or Ctrl + Win + D […]

Read More
Windows

Windows 11: Install PowerToys for 20+ Productivity Features

- 30.03.26 - ErcanOPAK comment on Windows 11: Install PowerToys for 20+ Productivity Features

⚑ Windows Superpowers Windows missing features? Microsoft’s PowerToys adds FancyZones, color picker, bulk rename, image resize, always-on-top, and 15+ more tools. Free, official, essential. Install PowerToys # Method 1: Microsoft Store (easiest) winget install Microsoft.PowerToys # Method 2: GitHub Release # Download from: https://github.com/microsoft/PowerToys/releases # After install, PowerToys runs in system tray # Right-click tray […]

Read More
AI

AI Prompt: Refactor Legacy Code to Modern Standards

- 30.03.26 - ErcanOPAK comment on AI Prompt: Refactor Legacy Code to Modern Standards

πŸ”§ Modernize Legacy Code Fast Inherited spaghetti code from 2010? 500-line function? No tests? AI refactors to modern patterns, breaks into testable units, explains every change. The Refactoring Prompt Refactor this legacy code to modern standards: Current code: [paste legacy code] Language/Framework: [JavaScript/Python/C#/etc.] Target version: [ES2023/Python 3.11/C# 12/etc.] Requirements: 1. Break down into smaller, single-responsibility […]

Read More
AI

AI Prompt: Optimize Slow SQL Queries with AI Analysis

- 30.03.26 - ErcanOPAK comment on AI Prompt: Optimize Slow SQL Queries with AI Analysis

πŸš€ 10 Second Query β†’ 0.1 Second Slow database query killing performance? Don’t know SQL optimization? AI analyzes query, suggests indexes, rewrites for massive speedup. The Query Optimization Prompt I have a slow SQL query that needs optimization. Current query: [paste your SQL query] Database: [PostgreSQL/MySQL/SQL Server/etc.] Table sizes: – users: 1 million rows – […]

Read More
AI

AI Prompt: Use AI as Senior Code Reviewer for Pull Requests

- 30.03.26 - ErcanOPAK comment on AI Prompt: Use AI as Senior Code Reviewer for Pull Requests

πŸ‘¨β€πŸ’» AI Senior Developer at Your Service No senior dev for code review? AI can spot bugs, security issues, performance problems. Acts like experienced tech lead reviewing your code. The Code Review Prompt Act as a senior software engineer conducting a thorough code review. Review this code for: 1. Bugs and logical errors 2. Security […]

Read More
Docker

Docker: Use Multi-Stage Builds to Reduce Image Size by 90%

- 30.03.26 - ErcanOPAK comment on Docker: Use Multi-Stage Builds to Reduce Image Size by 90%

πŸ“¦ Tiny Production Images 1.5GB Docker image? Build tools in production? Security nightmare. Multi-stage builds create small, secure images. Only runtime files shipped. The Problem: Bloated Images # ❌ Bad: Everything in one stage FROM node:18 WORKDIR /app # Install dependencies COPY package*.json ./ RUN npm install # Installs dev dependencies too! # Copy source […]

Read More
Kubernetes

Kubernetes: Use HPA to Auto-Scale Pods Based on CPU/Memory

- 30.03.26 - ErcanOPAK comment on Kubernetes: Use HPA to Auto-Scale Pods Based on CPU/Memory

πŸ“ˆ Auto-Scale Based on Load Fixed 3 replicas? CPU spikes, users wait. Traffic drops, you waste money. HPA (Horizontal Pod Autoscaler) scales pods automatically based on metrics. How HPA Works # deployment.yaml apiVersion: apps/v1 kind: Deployment metadata: name: web-app spec: replicas: 2 # Initial replicas template: spec: containers: – name: app image: myapp:latest resources: requests: […]

Read More
Wordpress

WordPress: Use REST API to Build Headless WordPress Applications

- 30.03.26 - ErcanOPAK comment on WordPress: Use REST API to Build Headless WordPress Applications

πŸš€ WordPress as Content API WordPress theme limiting you? Build React/Vue frontend, use WordPress as content source. REST API turns WordPress into headless CMS. Built-in Endpoints # All built-in, no setup needed! # Get all posts GET https://yoursite.com/wp-json/wp/v2/posts # Get single post GET https://yoursite.com/wp-json/wp/v2/posts/123 # Get pages GET https://yoursite.com/wp-json/wp/v2/pages # Get categories GET https://yoursite.com/wp-json/wp/v2/categories # […]

Read More
Wordpress

WordPress: Use WP-CLI for Command-Line Site Management

- 30.03.26 - ErcanOPAK comment on WordPress: Use WP-CLI for Command-Line Site Management

⚑ Manage WordPress from Terminal Clicking through admin for every site update? Slow. WP-CLI lets you install plugins, update core, manage usersβ€”all from command line. 10x faster. Install WP-CLI # Download curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar # Make executable chmod +x wp-cli.phar # Move to PATH sudo mv wp-cli.phar /usr/local/bin/wp # Test wp –info πŸš€ Essential Commands […]

Read More
Photoshop

Photoshop: Convert to Smart Objects for Non-Destructive Editing

- 30.03.26 - ErcanOPAK comment on Photoshop: Convert to Smart Objects for Non-Destructive Editing

πŸ›‘οΈ Edit Without Destroying Pixels Resize image 10 times? Quality destroyed. Apply filters? Can’t undo later. Smart Objects preserve original data. Edit infinitely without loss. The Pixel Destruction Problem ❌ Normal Layer Resize smaller β†’ Pixels deleted Resize bigger β†’ Blurry Apply filter β†’ Permanent Transform β†’ Quality loss βœ… Smart Object Original data preserved […]

Read More
Photoshop

Photoshop: Use Layer Comps to Save Multiple Design Variations

- 30.03.26 - ErcanOPAK comment on Photoshop: Use Layer Comps to Save Multiple Design Variations

🎨 Multiple Designs in One File Save 10 versions of same design? 10 PSD files? Chaos. Layer Comps save visibility, position, effects in snapshots. One file, infinite variations. What Are Layer Comps? Think of them as snapshots of your layers panel. Save current state, make changes, save another state. Switch between them instantly. 🎯 What […]

Read More
Visual Studio

Visual Studio: Use Live Unit Testing for Instant Test Feedback

- 30.03.26 - ErcanOPAK comment on Visual Studio: Use Live Unit Testing for Instant Test Feedback

βœ… See Test Results While You Type Manually running tests after every change? Slow. Live Unit Testing runs tests automatically, shows results inline as you code. What Is Live Unit Testing? Visual Studio Enterprise feature that runs unit tests in background and displays results in real-time with inline icons: πŸ“Š Inline Indicators Icon Meaning βœ“ […]

Read More
C#

C#: Use Span for High-Performance Memory Operations

- 22.03.26 - ErcanOPAK comment on C#: Use Span for High-Performance Memory Operations

πŸš€ Zero-Allocation String Operations Substring creates new string. Array slicing copies memory. Span<T> 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); // […]

Read More
C#

C#: Async/Await Best Practices – Avoid Common Mistakes

- 22.03.26 - ErcanOPAK comment on C#: Async/Await Best Practices – Avoid Common Mistakes

⚑ 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 […]

Read More
C#

C#: Use LINQ Efficiently – Avoid Common Performance Pitfalls

- 22.03.26 - ErcanOPAK comment on C#: Use LINQ Efficiently – Avoid Common Performance Pitfalls

⚑ 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 […]

Read More
C#

C#: Use Pattern Matching for Cleaner Type Checks and Switches

- 22.03.26 - ErcanOPAK comment on C#: Use Pattern Matching for Cleaner Type Checks and Switches

🎯 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) […]

Read More
Page 1 of 69
1 2 3 4 5 6 … 69 Next Β»

Posts navigation

Older posts
April 2026
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
27282930  
« Mar    

Most Viewed Posts

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

Recent Posts

  • C#: Use Init-Only Setters for Immutable Objects After Construction
  • C#: Use Expression-Bodied Members for Concise Single-Line Methods
  • C#: Enable Nullable Reference Types to Eliminate Null Reference Exceptions
  • C#: Use Record Types for Immutable Data Objects
  • SQL: Use CTEs for Readable Complex Queries
  • SQL: Use Window Functions for Advanced Analytical Queries
  • .NET Core: Use Background Services for Long-Running Tasks
  • .NET Core: Use Minimal APIs for Lightweight HTTP Services
  • Git: Use Cherry-Pick to Apply Specific Commits Across Branches
  • Git: Use Interactive Rebase to Clean Up Commit History Before Merge

Most Viewed Posts

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

Recent Posts

  • C#: Use Init-Only Setters for Immutable Objects After Construction
  • C#: Use Expression-Bodied Members for Concise Single-Line Methods
  • C#: Enable Nullable Reference Types to Eliminate Null Reference Exceptions
  • C#: Use Record Types for Immutable Data Objects
  • SQL: Use CTEs for Readable Complex Queries

Social

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