Reputation: 81262
I have a generic class that looks like this:
public interface IStationProperty
{
int Id { get; set; }
string Desc { get; set; }
object Value { get; }
Type ValueType { get; }
}
[Serializable]
public class StationProp<T> : IStationProperty
{
public StationProp()
{
}
public StationProp(int id, T val, string desc = "")
{
Id = id;
Desc = desc;
Value = val;
}
public int Id { get; set; }
public string Desc { get; set; }
public T Value { get; set; }
object IStationProperty.Value
{
get { return Value; }
}
public Type ValueType
{
get { return typeof(T); }
}
The property that gets the type is:
public Type ValueType
{
get { return typeof(T); }
}
So in my code, I have a loop pulling values (as string) from the db, here I want to do a type conversion (on the left side) so I can do a reliable value comparison.
I would like something like this:
var correctlyTypedVariable = (prop.ValueType) prop.Value;
I know this kind of thing has to be possible.
Upvotes: 0
Views: 104
Reputation: 4692
With IComparable:
public interface IStationProperty : IComparable<IStationProperty>
{
int Id { get; set; }
string Desc { get; set; }
object Value { get; }
Type ValueType { get; }
}
[Serializable]
public class StationProp<T> : IStationProperty where T : IComparable
{
public StationProp()
{
}
public StationProp(int id, T val, string desc = "")
{
Id = id;
Desc = desc;
Value = val;
}
public int Id { get; set; }
public string Desc { get; set; }
public T Value { get; set; }
object IStationProperty.Value
{
get { return Value; }
}
public Type ValueType
{
get { return typeof(T); }
}
public int CompareTo(IStationProperty other)
{
if (other.ValueType == typeof(string))
{
return Value.CompareTo((string)other.Value);
}
else if (other.ValueType == typeof(int))
{
return Value.CompareTo((int)other.Value);
}
else if (other.ValueType == typeof(double))
{
return Value.CompareTo((double)other.Value);
}
throw new NotSupportedException();
}
}
Upvotes: 0
Reputation: 7320
You already have
public T Value { get; set; }
which returns the typed value. If on the following code, the prop object is of type IStationProperty
var correctlyTypedVariable = (prop.ValueType) prop.Value;
then maybe your problem is on the interface : you should better use a generic one :
public interface IStationProperty
{
int Id { get; set; }
string Desc { get; set; }
Type ValueType { get; }
}
public interface IStationProperty<T> : IStationProperty
{
T Value { get; }
}
Upvotes: 2