I have a situation whereby I'm using a library that's been generated to provide an XML interface in C# based upon an XSD file run through xsd.exe.

The XML is structured as so.


When I'm actually working with this XML (which is mapped into internal memory objects thanks to the library) I have a lot of code that applies to all models. For example I may know that I can look for a field called FinalResult in all four models.

If I had control over the classes that represent the models, I could refactor it so it would make more sense but the code that is generated treats these four models as separate entities, and the parent is only a parent in the sense that it has variables that point to its "children", not in an OOP sense.

So far as I can tell, this means I could use something like the dynamic keyword in C# and avoid code duplication, or rewrite the code multiple times to have type safety, being forced to do so by the fact I don't have control over the external library.


Yes, you can.

The dynamic keyword in C# allows you to reference only those members of the object that are relevant to you. You can reference the members that are common to all of your types, and pretty much treat the objects equally:

foreach (dynamic result in Results)

So long as you don't mind the absence of intellisense, it will operate just as if you had used a strongly-typed object. The only difference is that binding of the member (and type checking) will occur at run time instead of compile time.

In the example above, as long as FinalResult has the same type in all of your objects, the list will never know the difference.

Note that you could do the same thing without dynamic, but it would require your Result classes to inherit from an Interface containing the common members:

foreach (IResult result in Results)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.