StructuralC#verifiedVerified

Proxy Pattern in C#

Provides a surrogate or placeholder for another object to control access, add lazy initialization, caching, logging, or access control.

How to Implement the Proxy Pattern in C#

1Step 1: Define the subject interface

public interface IImage
{
    string Display();
}

2Step 2: Real subject (expensive to create)

public class HighResImage(string filename) : IImage
{
    private readonly string _data = $"[Heavy data for {filename}]";

    public string Display() => $"Displaying {filename}: {_data}";
}

3Step 3: Proxy delays creation until first use (lazy loading)

public class ImageProxy(string filename) : IImage
{
    private HighResImage? _realImage;

    public string Display()
    {
        _realImage ??= new HighResImage(filename);
        return _realImage.Display();
    }
}

// Usage:
// IImage image = new ImageProxy("photo.jpg");
// // Image not loaded yet
// Console.WriteLine(image.Display()); // Now loaded

Proxy Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Proxy Pattern in the Real World

A corporate receptionist acts as a proxy for the CEO. When someone wants to meet the CEO, the receptionist checks credentials, schedules the meeting, and logs the visit before granting access. The visitor interacts with the receptionist using the same protocol they would use with the CEO—the receptionist simply adds control and record-keeping around that access.