Search code examples
c#objectusing

Closing an object inside the objects using statement


I'm trying to find out if I can close a stream like this inside a using statement and open another?

Here is the code:

string combined = Path.Combine(path, some + ".txt");
if (File.Exists(combined))
{
    using (TextReader obj2 = new StreamReader(combined))
    {
        string line = obj2.ReadLine();
        if (line != null && !line.Contains("Mon"))
        {   
            obj2.Close();
            TextWriter obj = File.AppendText(combined);
            obj.WriteLine("Mon\t\t\t|Thue\t\t\t|Wedn\t\t\t|Thurs\t\t\t|Friday\t\t\t|Sat\t\t\t|Sun\t\t\t    ");
            obj.Close();
        }
    }
}

Solution

  • Regardless if it's possible and what happens, just don't do it. Why? Because:

    1. it's ugly,
    2. it's against the purpose of the using statement,
    3. it's barely readable code,
    4. it's poorly maintainable,
    5. it's not undestandable by anyone else, and not even by yourself starting from tomorrow,
    6. it's an apparent code smell — an indication you hardly know what you are doing and that you are struggling with structuring your code properly.

    Update: The direct consequence of points (3) and (5) above is that I misunderstood your code and thought you were assigning the new instance of TextReader into obj2. I just didn't spot there was some other variable obj with a barely different name.