Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# constructor using a dynamic vs Interface as a parameter

In the benefit of creating clean decoupled code in c# I was hoping to get some feedback on using a dynamic parameter to construct objects. Typically I believe you'd create an interface and use the interface as the contract, but then you have to create interfaces for all your classes which I think is kind of icky...

So, my question is what are the pros and cons of doing something like this:

class Class1
{
    public string Description { get; set; }
    public string Name { get; set; }

    public Class1(dynamic obj)
    {
        Name = obj.Name;
        Description = obj.Description;
    }
}

vs

class Class1
{
    public string Description { get; set; }
    public string Name { get; set; }

    public Class1(IClass1 obj)
    {
        Name = obj.Name;
        Description = obj.Description;
    }
}
like image 483
Aaron Barker Avatar asked May 25 '11 17:05

Aaron Barker


1 Answers

Pros of the interface:

  • The compiler will tell you if you're using the wrong kind of argument
  • The signature of the constructor tells you what's required from the parameter

Pros of dynamic:

  • You don't need to declare the interface or implement it
  • Existing classes with Name and Description properties can be used with no change
  • Anonymous types can be used within the same assembly if they have Name and Description properties

Personally I typically use C# as a statically typed language unless I'm interacting with something naturally dynamic (e.g. where I'd otherwise use reflection, or calling into COM or the DLR)... but I can see that in some cases this could be useful. Just don't over-do it :)

like image 69
Jon Skeet Avatar answered Sep 21 '22 22:09

Jon Skeet