2

I need to add some information to a class of type DataRecord

I would like to embed in every instance inheriting from IDataRecord a Dictionary

Is it possible to achieve this using Extension Fields? (something like Extension Method)

Revious
  • 7,816
  • 31
  • 98
  • 147
  • 1
    You could emulate it with extension methods but that would be horrible. – user703016 Mar 19 '14 at 15:54
  • @presiuslitelsnoflek: can you explain better why? – Revious Mar 19 '14 at 15:55
  • 1
    possible duplicate of [Does C# have extension properties?](http://stackoverflow.com/questions/619033/does-c-sharp-have-extension-properties) – Paolo Moretti Mar 19 '14 at 15:57
  • 1
    Most likely you wouldn't really want to add this data in a 'global' context, but rather in a very specific context in which the data is being used. Given that is the case, consider creating a class for that context and have it store a `Dictionary` with whatever extra data you need to associate with each record to achieve the logic you're after. This is much better than an 'extension field' as it's not global in scope (as long as you don't make your context a global Singleton, which you should most likely avoid doing.) – Dan Bryant Mar 19 '14 at 15:59

2 Answers2

3

No, there is no such feature in C#.

It wouldn't really make sense to add it either, as there wouldn't be a well defined location to store the data for that field. Dynamically increasing the size of an existing object isn't really feasible, given the design of the language. It's important that the size of all object instances is constant.

Servy
  • 202,030
  • 26
  • 332
  • 449
3

No, this is not possible. Extension methods are nothing more than static methods which are passed the object as this reference.

Alternatives:

  • Extension method which uses some sort of static Dictionary
  • Maybe use mixin libraries (e.g. re-mix of http://www.re-motion.org)
  • Use a common base class?
  • Use a wrapper, e.g. ClassWithDictionary<MyClassA> which kind of decorates the original object
D.R.
  • 20,268
  • 21
  • 102
  • 205