Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C# C# Streams and Data Processing Serialization Serializing to a File

What is "using" for? Can I skip it? Example: "using(StreamWriter writer = new StreamWriter(fileName))".

What benefits does it give?

Program.cs
using System;
using System.IO;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace Treehouse.CodeChallenges
{
    public class Program
    {
        public static void Main(string[] arg)
        {
        }

       public static void SerializeWeatherForecasts(List<WeatherForecast> weatherForecasts, string fileName)
       {
           var serializer = new JsonSerializer();
           using(StreamWriter writer = new StreamWriter(fileName))
           using(JsonTextWriter jsonWriter = new JsonTextWriter(writer))
           {
               serializer.Serialize(jsonWriter, weatherForecasts);
           }
       }

       public static WeatherForecast ParseWeatherForecast(string[] values)
       {
            var weatherForecast = new WeatherForecast();
            weatherForecast.WeatherStationId = values[0];
            DateTime timeOfDay;
            if (DateTime.TryParse(values[1], out timeOfDay))
            {
                weatherForecast.TimeOfDay = timeOfDay;
            }
            Condition condition;
            if (Enum.TryParse(values[2], out condition))
            {
                weatherForecast.Condition = condition;
            }
            int temperature;
            if (int.TryParse(values[3], out temperature))
            {
                weatherForecast.Temperature = temperature;
            }
            double precipitation;
            if (double.TryParse(values[4], out precipitation))
            {
                weatherForecast.PrecipitationChance = precipitation;
            }
            if (double.TryParse(values[5], out precipitation))
            {
                weatherForecast.PrecipitationAmount = precipitation;
            }
            return weatherForecast;
        }

        public static List<WeatherForecast> DeserializeWeather(string fileName)
        {
            var weatherForecasts = new List<WeatherForecast>();

            using (var reader = new StreamReader(fileName))
            using (var jsonReader = new JsonTextReader(reader))
            {
                var serializer = new JsonSerializer();
                weatherForecasts = serializer.Deserialize<List<WeatherForecast>>(jsonReader);
            }

            return weatherForecasts;
        }
    }
}
WeatherForecast.cs
using System;
using Newtonsoft.Json;

namespace Treehouse.CodeChallenges
{
    public class WeatherForecast
    {
        [JsonProperty(PropertyName = "weather_station_id")]
        public string WeatherStationId { get; set; }
        [JsonProperty(PropertyName = "time_of_day")]
        public DateTime TimeOfDay { get; set; }
        public Condition Condition { get; set; }
        public int Temperature { get; set; }
        [JsonProperty(PropertyName = "precipitation_chance")]
        public double PrecipitationChance { get; set; }
        [JsonProperty(PropertyName = "precipitation_amount")]
        public double PrecipitationAmount { get; set; }
    }

    public enum Condition
    {
        Rain,
        Cloudy,
        PartlyCloudy,
        PartlySunny,
        Sunny,
        Clear
    }
}

2 Answers

You can use this using statement with any type that implements the IDisposable Interface. Every type that includes the IDispose() method (from IDiposable) must be removed from memory by the user code (your code). This just means that you have to call the Close() method on it then you don't need the object anymore. You can do the same by initializing the object in the using statement.

You could do the same thing with Close():

StreamWriter writer = new StreamWriter(fileName);
// end of the method
writer.Close();

After the closing bracket the object is removed from the memory. This is also important then you want to connect to local or remote Database. If you don't close it other programs can not access the Database

Thank you, Hakim! Summarizing what you said. We can use using():

1) With objects that implement IDisposable interface.

2) To save memory.

3) To connect to a database later.

4) Save time to write object.close();

Don't get me wrong with the example of a Database. This was just an example which I come across a lot of times. So instead of serializing to a JSON or XML file you can save data on a database (read and write).

  • The using statement clearly defines the scope of the variable (resource).