hvitorino
hvitorino

Reputation: 23

Why anonymous types have internal visibility in C#?

Is this because of security issues that could happen if anonymous types were public? I just don't get.

That's the kind of code I wanted to be supported by the language

Assembly 1

public class Renderer
{
    public void RenderHtmlInput(dynamic inputModel)
    {
        var html = string.format("<input type='text' width='{0}' height='{1}'>", inputModel.width, inputModel.height);
        ...
    }
}

Assembly 2

public class Consumer
{
    public void Run()
    {
        var renderer = new Renderer();

        renderer.RenderInput(new { width = "12px", height = "20px" });
    }
}

Upvotes: 2

Views: 807

Answers (1)

linkerro
linkerro

Reputation: 5458

Because you're supposed to use them in the same library. It's not ok to expose anonymous types over interfaces or class boundaries.

If you want to do that, use dynamic types.

Edit: Anonymous types also have their names automatically generated, so exposing them from a library means they can conflict with anonymous types from another library.

Upvotes: 3

Related Questions