I mentioned in my Introduction post of this series the TypeConverters
Overview: For those who don't know what is a TypeConverter you can expect that it is something responsible to convert between types, there are times when you need to convert from one data type to another. Type converters are classes that describe how a particular object converts to and from other data types. For example, to display a date on the screen(console, windows form, web ..) it will need to be converted to a string representation. Vice Versa is true, if there is a string value of a date that needs to be stored for example in database. Usually casting is enough when the types are simple. But with complex types, a better technique is used.
TypeConverters are classes that define how an object converts to and from other types. Which are used during design time for sting conversion ( used by the PropertyGrid ), also in runtime in validations and conversions.
So, first lets take a look on some of the Common .NET Type Converters that are already built for us to use.
All the following classes are in the System.ComponentModel and the System.Drawing namespaces.
- StringConverter
- BooleanConverter
- CharConverter
- CollectionConverter
- CultureInfoConverter
- DateTimeConverter
- EnumConverter
- ExpandableObjectConverter
- GuidConverter
- TimeSpanConverter
- ColorConverter
- FontConverter
- PointConverter
- RectangleConverter
- SizeConverter
And much more. [more]
From the most Converters that I personally like is the ExpandableObjectConverter you can apply it using the following syntax.
Example:
[code:c#]
public class Info
{
int i;
string s;
public int IntProperty
{
get { return i;}
set { i = value; }
}
public int StringProperty
{
get { return s; }
set { s = value; }
}
}
public class ButtonEx : Button
{
…
private Info i;
[TypeConverter(typeof(ExpandableObjectConverter))]
public Info ComplexObject
{
get { return i; }
set { i = value; }
}
}
[/code]
Without the attribute, the property would look like this | |
After applying the converter it is like this |
Next part I will implement a custom converter.
Leave a Reply