다음을 통해 공유


Brain Teaser #3

This brain teaser also comes courtesy of Simeon Cran.

What will the following code output? When you think you know, copy the code into Foo.cs and run “csc Foo.cs” and then run “Foo.exe”. Did it output what you expected? The brain teaser is to come up with the correct explanation for why the program outputs what it does.

 using System;

struct Foo : IDisposable
{
    bool disposed;
    
    public void Dispose()
    {
        disposed = true;
        Console.WriteLine("Disposed");
    }

    static void Main(string[] args)
    {
        Foo foo;
        using (foo = new Foo())
        {
        }
        Console.WriteLine(foo.disposed);
        using (foo = new Foo())
        {
            foo.Dispose();
        }
        Console.WriteLine(foo.disposed);
    }
}

Comments

  • Anonymous
    May 07, 2008
    Make your struct to a class and it should work as expected. Structs are copy by value and not reference.
  • Anonymous
    May 07, 2008
    The comment has been removed
  • Anonymous
    May 07, 2008
    The comment has been removed
  • Anonymous
    May 07, 2008
    You've been kicked (a good thing) - Trackback from DotNetKicks.com
  • Anonymous
    May 08, 2008
    The comment has been removed
  • Anonymous
    May 08, 2008
    The comment has been removed
  • Anonymous
    May 09, 2008
    The comment has been removed
  • Anonymous
    May 09, 2008
    Boxing is not the answer. If it was boxing, this code would print “Hits: 2” but it doesn’t:using System;struct Foo : IDisposable{   int hitCounter;   public void HitMe()   {       hitCounter++;   }   public void Dispose()   {       Console.WriteLine("Hits: " + hitCounter);   }   static void Main(string[] args)   {       Foo foo;       using (foo = new Foo())       {           foo.HitMe();           foo.HitMe();       }   }}
  • Anonymous
    May 09, 2008
    The comment has been removed
  • Anonymous
    July 21, 2008
    Ultram. Can you snort ultram. Ultram side effects.