Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# object metadata

Tags:

c#

object

Is there any way to glue metadata to an object in C#?

Context: Framework which is sending messages between peers over the network. Messages can be arbitrary serializable user-defined .NET types.

Of course, when a message is sent by a peer, the framework could wrap the object into a Message class which saves the metadata, and the receiver could unwrap it. However, the processing method of the peer could decide to resend the message to another peer - however, I want to keep the original metadata. The user should not be required to use Message.RealMessage all the time except when resending it.

I thought about keeping the wrapped instance in a dictionary and upon resending looking up if there is already a wrapped instance in the dictionary and resending that one, however, as messages may not be resent at all (or resent multiple times) this would require more and more memory.

Any solutions? Maybe C# directly supports gluing additional information to an object? Normally I would go for an internal interface, however, the user would have to derive all its classes from a framework's base class, which is not possible.

Edit: I kind of want to say "here is an object of WrappedMessage but you are only allowed to use the interface provided by the class T".

like image 360
D.R. Avatar asked Oct 21 '22 02:10

D.R.


1 Answers

There is the ConditionalWeakTable that should do what you want a little better than using directly a Dictionary.

To quote:

Enables compilers to dynamically attach object fields to managed objects.

You can ignore the part about the class being for compiler :-)

like image 158
xanatos Avatar answered Oct 27 '22 11:10

xanatos