Vinayak
Vinayak

Reputation: 3

Returning a nested class from inherited class

New to c# and trying to follow a specific code structure in building a weather API

  public class weatherData
   {
    public class coordinates
    {
        protected string longitude;   //coord.lon for opw
        protected string latitude;    //coord.lat for opw
    }

    public class weather
    {
        protected string summary;     //weather.main for opw
        protected string description;
        protected double visibility;  // only for  DS
    } }

    public class weatherAPI : weatherData
{


}

I'm trying to write a return function for coordinates(returns both latitude and longitude), weather(returns summary, description, visibility) in weatherAPI.

Please help. Thanks !

Upvotes: 0

Views: 154

Answers (1)

CodeCaster
CodeCaster

Reputation: 151594

You're not looking for nested classes or inheritance. Both have their place, but that's not here. See:

You're looking for composition, using properties. And while you're at it, adhere to C# naming conventions and use properties wherever possible:

public class Coordinates
{
    public string Longitude { get; set; }   //coord.lon for opw
    public string Latitude { get; set; }    //coord.lat for opw
}

public class Weather
{
    public string Summary { get; set; }     //weather.main for opw
    public string Description { get; set; }
    public double Visibility { get; set; }  // only for  DS
} 

// A composed class 
public class WeatherData
{
    public Coordinates Coordinates { get; set; }
    public Weather Weather { get; set; }
}

Now you can write your method:

public class WeatherAPI
{
    public WeatherData GetWeatherData()
    {
        var data = new WeatherData();
        data.Coordinates = new Coordinates
        {
            Longitude = ...,
        };
        data.Weather = new Weather
        {
            Summary = ...,
        };

        return data;
    }
}

Upvotes: 3

Related Questions