Implementing Interfaces in Structures

Problem
You want to know if it’s permitted to define structures that implement interfaces.

Solution
Steer clear of defining structures that implement interfaces. If you must implement an interface in a structure, don’t assign fields from inside the interface methods.

Comments
The reason for this guideline is that C# boxes a structure when it’s accessed via an interface variable. You want to avoid boxing operations because they add overhead and consume memory.

Example

// Not recommended: If the code in the method modifies a field, the changes aren't propagated to the original structure.
interface IPerson {
    void SetName(string name);
}

struct User : IPerson {
    public string Name;

    // This method modifies a field.
    public void SetName(string name) {
        this.Name = name;
    }
}

class App {
    static void Main() {
        User user = new User();
        Initialize(user, "Jason"); // Hidden box operation.
        Console.WriteLine(user.Name); // Name is still empty!
    }

    static void Initialize(IPerson user, string name) {
        user.SetName(name);
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s