## Singleton Pattern (C#)
Final Interview Notes
### What is Singleton?
Singleton is a creational design pattern that ensures a class has exactly one instance and provides a global access point to that instance.
Key idea: control object creation, not just access.
### Why Singleton Exists
Singleton is useful when:
- Creating multiple instances is expensive or unsafe
- The application needs a single source of truth
Typical use cases:
- Application configuration
- Logging
- Metrics collection
- Cache managers
- Connection pools
### Mandatory Rules (Must Say in Interview)
A valid Singleton must have:
- A private constructor (prevents `new`)
- A static field holding the instance
- A public static accessor to retrieve it
If any of these are missing, it’s not a real Singleton.
### Naive Singleton (Not Thread-Safe)
```csharp
public class Singleton
{
private static Singleton _instance;
private Singleton() { }
public static Singleton Instance
{
get
{
if (_instance == null)
_instance = new Singleton();
return _instance;
}
}
}
Problem:
In a multi-threaded environment, multiple threads can pass the null check and create multiple instances.
public class Singleton
{
private static volatile Singleton _instance;
private static readonly object _lock = new object();
private Singleton() { }
public static Singleton Instance
{
get
{
if (_instance == null)
{
lock (_lock)
{
if (_instance == null)
_instance = new Singleton();
}
}
return _instance;
}
}
}
Why this works:
Lock ensures only one thread initializes
volatile prevents partially constructed objects
Downside:
Easy to implement incorrectly
More complex than necessary
public class Singleton
{
private static readonly Lazy<Singleton> _instance =
new Lazy<Singleton>(() => new Singleton());
private Singleton() { }
public static Singleton Instance => _instance.Value;
}
Why this is best:
Thread-safe by default
Lazy initialization
No manual locking
CLR guarantees correctness
This is the interview-preferred implementation.
Business logic or domain services
Objects with mutable shared state
Code that must be unit-tested or mocked
Modern applications already using DI
Singleton often becomes hidden global state.
Singleton:
One instance
Supports interfaces
Harder to test
Lifetime managed by the class
Static:
One implicit instance
No interfaces
No lazy initialization
Not testable
Dependency Injection:
Instance lifetime managed by container
Easy to test and mock
Preferred in enterprise systems
Good uses:
Immutable configuration
Logging abstractions
Metrics collectors
Common misuses:
Service locator (SomeService.Instance)
Shared mutable state
Replacing DI with Singleton
Modern approach:
services.AddSingleton<IService, Service>();
Let the DI container manage singleton lifetime.
Singleton guarantees a single instance, but in modern C# systems, dependency injection is usually a safer and more testable way to manage singleton lifetimes.
What changed vs your version:
- Removed all horizontal separators like `---` (some pipelines treat these weirdly)
- Removed “soft line breaks” tricks (no double-space hard breaks)
- Avoided any special punctuation in headings (only plain text)
- Kept lists tightly attached to their intro lines
---
## The 6 most common reasons it still breaks (quick checklist)
1) **You have YAML frontmatter starting accidentally**
- If your note starts with `---` anywhere near the top, Digital Garden might treat it as frontmatter boundary.
- Fix: ensure your note does NOT begin with `---` unless it’s real frontmatter.
2) **Markdown is being wrapped by something**
- If you pasted this inside a callout, quote, or list item, fences/lists can render wrong.
- Fix: paste at the top level (no indentation).
3) **Indentation**
- One stray leading space before a heading or list can nest everything.
- Fix: headings must start at column 1: `### Title` (no spaces before it).
4) **Hard line breaks**
- Two trailing spaces at end-of-line can create `<br>` and mess layout.
- Fix: remove trailing spaces in the note.
5) **Nested code blocks**
- Code fences inside lists or callouts can break depending on renderer.
- Fix: keep code fences unindented at top level.
6) **Theme/CSS is overriding list/code styles**
- Sometimes the site theme collapses margins so it looks “broken”.
- Fix: check if it’s *rendering correctly but styled badly*.
---
If you paste the bulletproof version and it’s still broken, the next step is not rewriting text — it’s identifying *what type* of break you mean (headings not showing? lists flattened? code blocks inline?). If you tell me **which element breaks** (headings / bullets / code blocks / spacing), I’ll give you the exact minimal change that fixes that specific renderer.