C# Assigning default property for class and operator =
You could create an implicit operator overload. Then you can create StringField
from strings like this:
StringField field = "value of new object";
string value=(string)field;
Know that this creates a new StringField
object. I wouldn't necessarily advice you to do this.
[System.Diagnostics.DebuggerDisplay("{Value}")]
public class StringField
{
public string Value { get; set; }
public static implicit operator StringField(string s)
{
return new StringField { Value = s };
}
public static explicit operator string(StringField f)
{
return f.Value;
}
public override string ToString()
{
return Value;
}
}
Re data-binding, for some binding targets (PropertyGrid
, DataGridView
, etc), you can do this with a TypeConverter
(see below). Unfortunately, this doesn't seem to work with TextBox
, so I think your best option is to simply add a shim property (as already suggested):
string NameString
{
get { return Name.Value; }
set { Name.Value = value; } // or new blah...
}
(and bind to NameString
)
In the past, I have used custom PropertyDescriptor
implementations to side-step this, but it isn't worth it just for this.
Anyway, a TypeConverter
example (works with PropertyGrid
and DataGridView
):
[TypeConverter(typeof(StringFieldConverter))]
public class StringField
{
public StringField() : this("") { }
public StringField(string value) { Value = value; }
public string Value { get; private set; }
}
class StringFieldConverter : TypeConverter
{
public override bool CanConvertFrom(
ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string)
|| base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(
ITypeDescriptorContext context,
System.Globalization.CultureInfo culture,
object value)
{
string s = value as string;
if (s != null) return new StringField(s);
return base.ConvertFrom(context, culture, value);
}
public override bool CanConvertTo(
ITypeDescriptorContext context, Type destinationType)
{
return destinationType == typeof(string)
|| base.CanConvertTo(context, destinationType);
}
public override object ConvertTo(
ITypeDescriptorContext context,
System.Globalization.CultureInfo culture,
object value, Type destinationType)
{
if (destinationType == typeof(string) && value != null
&& value is StringField)
{
return ((StringField)value).Value;
}
return base.ConvertTo(context, culture, value, destinationType);
}
}