I would like to implement conversion between two library classes by Convert.ChangeType in C#. I can change neither of the two types. For example converting between Guid and byte[].
Guid g = new Guid();
object o1 = g;
byte[] b = (byte[]) Convert.ChangeType(o1, typeof(byte[])); // throws exception
I am aware that Guid provides a ToByteArray() method, but I would like to have that called when Guid is converted to byte[]. The reason behind this is that the conversion also takes place in library code (AseDataAdapter) which I can not modify. So is it possible to define a conversion rule between two types without modifying the sourcecode of either of the two classes?
I was experimenting with TypeConverter, but doesn't seem to work either:
Guid g = new Guid();
TypeConverter tc = TypeDescriptor.GetConverter(typeof(Guid));
byte[] b2 = (byte[])tc.ConvertTo(g, typeof(byte[])); // throws exception
The variable tc gets set to System.ComponentModel.GuidConverter which doesn't support conversions to byte[]. Can I have two TypeConverters for the same class? Even if I could, wouldn't I need to prepend an attribute to the source code of the class to assign a TypeConverter?
Thanks