Search code examples
c#.netmethodsstructural-typing

C# method that accepts multiple objects that have common properties?


I have several objects with a few properties that are common to all of them. For example:

Object A is of type X and it has 10 properties

Object B is of type Y and it has 15 properties

Object C is of type Z and it has 7 properties

All of these objects have "name", "signature" and "checksum" properties in common. I'm trying to create a static helper method that can accept an object of any type that contains "name", "signature" and "checksum" properties. Is that possible or do I actually need three different methods (one to accept an object of each type)?

EDIT - For what it's worth, I failed to mention that these objects are exposed to me via a web service.


Solution

  • I am going to assume that since these obejcts are exposed via a web service, then you have no control over the definition of the object. They are what they are and you can't have them inherit from a common base class, or interface. With that constraint to the problem, you really have only two options.

    If you are using C# 4.0 or later you can use the new dynamic type. This basically is an object reference that does not do any type evalutation until run time. So if a property or method you use on the dynamic type does not exist your going to get a run time error rather than a error during compliation.

    The other otpion is going to simply take a reference to type Object and use reflection to manipulate properties and methods. A lot of potential ugly there.

    I you are not using C# 4+ then I think I would go with the three seperate methods. While you might duplicate some code, I would rather have that than a bunch of complex hard to follow reflection calls that you would have to use in c# 3.5-