1

suppose I have an object user and I cannot edit its class. How can I add a simple property like username to the object?

Currently my implementation is a simple wrapper that is constructed using a user. The user then becomes a property of my wrapper object and the wrapper object contains a property named username. But it seems to me this is not the correct way to do it. Note the user object is not a dependencyobject and furthermore I am aware that extension method exists, but I do not believe extension method exists, but I need to store the username, so it cannot be static.

Any advice would be very welcome.

Snowflake
  • 2,869
  • 3
  • 22
  • 44
  • 1
    Inherit from User and add your property. Of course this assumes User class isn't sealed. Btw why do you think wrapping isn't the right way? IMO wrapping is the way to go. – Sriram Sakthivel Feb 11 '15 at 11:05
  • You can hold properties separately (in some kind of dictionary) from object. They will not be *properties* (technically). – Sinatr Feb 11 '15 at 11:13
  • If User is a `partial` class then you can define another `partial User` class to extend it – Tian van Heerden Feb 11 '15 at 11:22
  • Thanks, but it is not a partial class, nor can I simply inherit from user due to the lack of double inherence in C#. – Snowflake Feb 11 '15 at 11:32

1 Answers1

0

In a certain sense, you are asking for implementation of the Mixin pattern in C#, which cannot be implemented directly, as discussed in this question. However, it would be possible to create extension methods (namely a setter and getter) instead of a property of type T. As it is impossible to add a field, the value to be stored and returned could be saved behind the scenes in a Dictionary<User,T>; this approach does not actually permit a property, but it provides a solution which does not require User to be partial or deriving from User.

Community
  • 1
  • 1
Codor
  • 17,447
  • 9
  • 29
  • 56