TypeConverter question

G

Guest

Hello everybody,

I have a problem towards the following topic.

There is a class like MyColor and a class like MyRectangle that has a
property called FillColor which is of type MyColor. Now it should be able to
say

MyRectangle rect1 = new MyRectangle();
rect1.FillColor = "Red";

Therefore I need an implicit cast operator but this causes the loss of
further information that are hold in the MyColor object stored in
rect1.FillColor before. So I need to transfer further data than just a string
during conversion from the old object to the new object. Lets say the old
FillColor had a property called Remark with a value "Test-Remark". This
property would be empty after static implicit type conversion.

Is it possible to use the TypeConverter.CreateInstance method therefore? And
if yes, how exactly?

Users or other developers should be allowed to write rect1.FillColor =
"green" without calling the TypeConverter explicitly.

Thanks if anyone has help for me.

Matthias
Germany/Austria
 
N

Nicholas Paldino [.NET/C# MVP]

Matthias,

I don't agree that you should be able to specify the FillColor with a
string named "Red". I think that is bad design, since you have a strongly
typed static color instance on Colors named Red (i.e. Colors.Red).

Furthermore, implicit cast operators are bad news in cases like this
where there is not a direct correlation between the types. Int to long is
one thing, but string to color is not.

If you want to convert the Color instance to a string, use the
ColorConverter class, and it will properly serialize your color instance to
a string, and from a string back to the Color instance.

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top