0

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 !

Vinayak
  • 3
  • 3
  • Hello. Not exactly sure what your problem is? Can you further explain please. I can see your class designs, but what is it you can't do or are having problems with? – Wheels73 Aug 08 '18 at 08:33
  • I want to write a function inside weatherAPI, which can return the inherited classes (for egs coordinates). I will create an object of weatherAPI somewhere and calling that specified function for coordinates, returns the coordinate values (i.e longitude and latitude). – Vinayak Aug 08 '18 at 08:40
  • You refer to a nested class as `parent.nestedclass`. So in general something like `public weatherData.coordinates GetGoordinate()`. However in this case since the nested class is inside the class where you are declaring methods you could just use `public coordinates GetGoordinate()`. That having been said nested classes are very rarely what you want for good design. I would just have them all as separate classes. – Chris Aug 08 '18 at 08:48

1 Answers1

3

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;
    }
}
CodeCaster
  • 147,647
  • 23
  • 218
  • 272