Search code examples
c#abstractextendradix

C# abstract base class - extending the implementation


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!


Solution

  • 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;
                }
            }