Reputation: 43
I have the following case:
public class GeoLocation
{
public double Longitude { get; set; }
public double Latitude { get; set; }
public string LocationName { get; set; }
}
public abstract class Base
{
public abstract GeoLocation GeoLocation { get; set; }
}
public class Concrete : Base
{
public override GeoLocation GeoLocation
{
get;
set;
}
}
Now if I create a class Concrete2
which inherits from Base
as well and I want the GeoLocation
object to have 1 more property:
public string Address{ get; set; }
What is the best way to implement this?
I could create a new class called GeoLocationEx : GeoLocation
and place Address
property there but then in my Concrete2 object, I would have 2 properties: GeoLocation
and GeoLocationEx
which I do not like...
I could also make the GeoLocation class partial and extend it with Address
property for the Concrete2
class but I am not sure would this be a "proper" use of partial classes.
What could be the best way to do this?
Thanks in advance for your help!
Upvotes: 2
Views: 14303
Reputation: 106
You could probably use generics:
public class GeoLocation
{
public double Longitude { get; set; }
public double Latitude { get; set; }
public string LocationName { get; set; }
}
public class GeoLocationEx : GeoLocation
{
public double Address { get; set; }
}
public abstract class Base<T>
{
public abstract T GeoLocation { get; set; }
}
public class Concrete : Base<GeoLocation>
{
public override GeoLocation GeoLocation
{
get;
set;
}
}
public class Concrete2 : Base<GeoLocationEx>
{
public override GeoLocationEx GeoLocation
{
get;
set;
}
}
Upvotes: 2
Reputation: 34591
public class GeoLocation
{
public GeoLocation(GeoLocation obj) {/* implement a copy constructor */}
public GeoLocation() {/* default constructor */}
public double Longitude { get; set; }
public double Latitude { get; set; }
public string LocationName { get; set; }
}
public class GeoLocationEx : GeoLocation
{
public string Address { get; set; }
}
public abstract class Base
{
public abstract GeoLocation GeoLocation { get; set; }
}
public class Concrete2 : Base
{
private GeoLocationEx _geoLocation;
public override GeoLocation GeoLocation
{
get { return _geoLocation; }
set
{
_geoLocation = new GeoLocationEx(value);
}
}
}
Now inside the Concrete2
class you can work directly with the private GeoLocationEx
field. Also, you can expose additional public methods for Concrete2
-specific stuff.
Refer to MSDN on writing copy constructors: http://msdn.microsoft.com/en-us/library/ms173116(v=vs.80).aspx
Upvotes: 1