Hi, HashCode. Tell me, please, how can I add properties to the class in runtime? For example, I get a Dictionary or HashTable as input, and from the keys that they have, generate properties that would return key values. Is it possible? Thank.

  • only if you use dynamic - Specter
  • Properties, why it may need? And then refer to them as through reflection? I think the maximum you can do is override the indexer - rasmisha
  • one
    @Spectre, thank you, and at least I read about your sharpe. (although the realization of what the TS wants is not clear to me, tell me :)) - rasmisha
  • Personally, I would add the required method to your class, and if the class is not self-written, I would use extension methods. Well, if you do not like it, I recommend reviewing the architecture of your application. - megacoder
  • Hmm, thanks to all for the answers and comments, apparently, I absolutely got excited with the ideas. I will simply turn to the key and do not invent too much :). - lavrik_dndz

2 answers 2

Dynamically adding properties is quite a laborious process using .NET3.0. As already noted, it is also difficult to turn to the methods through reflection. The C # language is strongly typed, although there has been some recent shift in emphasis. If you are still interested, then look towards ExpandObject. Here is a small link to stackoverflow.com

  • The emphasis cannot be shifted. C# was a statically typed language with strong typing, and it remains, and dynamic is just syntactic sugar. - Costantino Rupert
  • I would not say that DLR is syntactic sugar - Specter
  • @Spectre Well, I certainly exaggerate, but it just seems to me that adding a special set of metadata and methods to working with this set should not be called a shift in emphasis. - Costantino Rupert
  • All the same, DLR is not the same as ExpandoObject . Runtime, through which a dynamic language like python can be interpreted, is clearly more than just syntactic sugar. Although, I think, to call the emergence of DLR offset C# also not true. Rather, the entire .NET platform as a whole, rather than C# . - Ilya Pirogov
  • Yes, it is not because of what is fashionable, it is rather a necessity. Strong typing will still remain the priority for me - Specter

And where are you going to use it? If with components like PropertyGrid , then implement in your ICustomTypeDescriptor object.