For example, an object of unknown type comes from the outside.

It is known that objects can be different (different fields), but this field always has one field.

Via Dynamic is a trivial task, and how was it done when it was not entered in C #?

UPD

An example of a code for working with Dapper, where columns are mapped

var codes = conn.Query<dynamic>(...sql and params here...) .Select<dynamic,Code>(s=>new Code{Id = s.Id, Type = s.Type, Value = s.code, Description = s.Description}); 
  • five
    matching things are a common interface. - vitidev
  • four
    reflection for example - Grundy
  • @Grundy, can I have a sample? - iluxa1810 September
  • one
    @ iluxa1810, you first need an example with dynamic, so that it is clear which part of the problem arises - Grundy
  • one

1 answer 1

Generally speaking, before the advent of dynamic, working with the logic of objects of unknown type (and knowing that an object has a certain attribute and, moreover, operations with it is, you want it or not, but working with logic) in a programming language with strict typing was considered bad form and bad practice. Some oldfags, like me, think so still.

But if you really need, then there are two options: inheritance and Reflection.

Inheritance is used in cases when you have control over the data model - then you can make either the base class or (even better) the interface with the required field, be inherited, paste it in the right place, and then work like a normal object.

The option with reflection is used if inheritance cannot be done or is not desirable - for example, we use a data model from an external library. In this case, we simply climb inside the object and with the help of reflection we tear out the necessary field.

Making this process in the implementation can be a variety of ways. You can use any framework that wraps several commands into one type of GetPropertyValue. You can make a class with the necessary fields and, using the auto-chopper (of which there is a great multitude), copy the fields of an unknown object into our object. You can throw all the fields of an unknown object into Dictionary and work with it already.