I've been looking for a more intuitive way of converting between datatypes in C# (like an enum to a string) So i stumbled upon the TypeConverter class. I've read the documentation on how to create one, and it seems fairly straightforward, just override a few methods from TypeConverter with some custom conversion logic and done.
However, ive been unable to figure out how to actually use this converter now that i've created it. every resource I've found simply explains how to create one, and the only reference ive seen to actually using it is decorating my type class with [TypeConverter(typeof(MyConverter))]
. The problem is I dont actually have a type class, my type im converting to/from is an enum and string, so i have no idea where im supposed to put the TypeConverter.
Hypothetically if my type was a custom class, and I put the decoration just on the class where its defined, how would I then convert the type? Do I just use the type as a string wherever i want and the converter will magically do its work without being asked or do i need to prompt it somehow. Is there a scope within which I can use the type converter or is it accessible anywhere that the type is?
I was kind of expecting this to work like System.Convert, but that doesnt seem to be the case.
TypeConverter
. – DysphagiaEnumConverter
is used automatically as the default converter for all enums, IIRC – BobolinkenumValue.ToString()
andEnumType enumValue; EnumValue.TryParse("StringValue", out enumValue);
won't suffice? – DysphagiaenumValue.ToString()
actually does work, and is all I need for this situation. I didnt even think of trying it because I was under the impression that enums were only available as a static list of integers during run-time. – Larousse