Post by Sonnich JensenCan I create a property as a string as well as a DateTime?
public string aaa....
public DateTime aaa....
I want to write it as a DateTime, and read it as a string.
The best I can think of is a class where I overwrite ToString
Any better ideas?
Well - you can obviously not have two properties with the same name.
I have two ideas.
1)
The pragmatic:
public class Foobar
{
private DateTime theTime;
public DateTime TheTimeAsDateTime
{
get { return theTime; }
set { theTime = value; }
}
public String TheTimeAsString
{
get { return theTime.ToString(); }
set { theTime = DateTime.Parse(value); }
}
}
It may not be so elegant. But it is very easy to understand. And
that should really be the main criteria. So this is what I would
do.
2)
The tricky:
public class DateTimeOrString
{
private DateTime dt;
private DateTimeOrString(DateTime dt)
{
this.dt = dt;
}
private DateTime Get()
{
return dt;
}
public static implicit operator DateTimeOrString(DateTime dt)
{
return new DateTimeOrString(dt);
}
public static implicit operator DateTimeOrString(String s)
{
return new DateTimeOrString(DateTime.Parse(s));
}
public static implicit operator DateTime(DateTimeOrString dts)
{
return dts.Get();
}
public static implicit operator String(DateTimeOrString dts)
{
return dts.Get().ToString();
}
}
public class Foobar
{
public DateTimeOrString TheTime { get; set; }
}
It may be elegant as it is almost invisible to the callers.
But how many C# developers are really familiar with implicit
operators. So risk of confusion and problems.
Arne