TerryLi
TerryLi

Reputation: 231

C# .NET Class member type based on another member type

There is a Class define a geometry which includes 2 members, "type", and "coordinates"

[DataContract]
public class geometry
{
    [DataMember]
    public string type = "LineString";

    [DataMember]
    public float coordinates;

}

Is there a way that the coordinates member type can be dynamically defined based on the value of "type"? for example, if the "type" is "MultiLineString" the coordinates type will be string?

Upvotes: 0

Views: 166

Answers (1)

p.s.w.g
p.s.w.g

Reputation: 148990

No, that's not possible. The closest you could get is to define a generic class like this:

[DataContract]
public class geometry<T> where T : struct
{
    [DataMember]
    public T coordinates;
}

And then use it like this:

var geom = new geometry<float>();
geom.coordinates = 1.0f;

If you really want to have the type member there, say, for serialization purposes, you could use something like this:

[DataContract]
public class geometry<T> where T : struct
{
    [DataMember]
    public readonly string type = typeof(T).Name;

    [DataMember]
    public T coordinates;
}

var geom = new geometry<float>();
Console.WriteLine(geom.type); // Single

Upvotes: 2

Related Questions