1

The following:

using (StreamReader reader = File.OpenText ("file.txt"))
{
 ...
}

is precisely equivalent to:

{
 StreamReader reader = File.OpenText ("file.txt");
 try
 {
 ...
 }
 finally
 {
 if (reader != null)
 ((IDisposable)reader).Dispose();
 }
}

My question is, did we explicitly typecast StreamReader object into IDisposable interface? Can one cast class types into interfaces? I don't understand what we gained from typecasting to interface since there is no implementation there. Code example is from the book I am reading.

miran80
  • 945
  • 7
  • 22

2 Answers2

4

is precisely equivalent to:

It's not, actually. What actually happens can't be represented in C#.

However, imagine this case:

public class MyDisposable : IDisposable
{
    public void Dispose()
    {
        Console.WriteLine("Class implementation");
    }
    void IDisposable.Dispose()
    {
        Console.WriteLine("Explicit implementation");
    }
}

If you write using (new MyDisposable()) { }, then it will print "Explicit implementation".

That is, a using statement will call the actual implementation of IDisposable.Dispose. Calling MyDisposable.Dispose() will however print "Class implementation".

This is what the cast ((IDisposable)reader).Dispose() is showing -- this equivalent C# code is calling the Dispose method which implements IDisposable.Dispose().


However, if the disposable object is a struct, then the C# code ((IDisposable)mystruct).Dispose() will box it. A using statement will however not box structs.

Given:

public struct MyDisposableStruct : IDisposable
{
    public void Dispose()
    {
        Console.WriteLine("Class implementation");
    }
    void IDisposable.Dispose()
    {
        Console.WriteLine("Explicit implementation");
    }
}

It is not possible to write C# code to get it to print "Explicit implementation" without also boxing the struct. This however what a using statement does.

canton7
  • 37,633
  • 3
  • 64
  • 77
  • Besides ability to implement 2 interfaces that have method names with same signature, what would be a practical reason to explicitly implement interface methods? – miran80 Jan 09 '20 at 15:16
  • 1
    @miran80 See https://stackoverflow.com/questions/143405/c-sharp-interfaces-implicit-implementation-versus-explicit-implementation – canton7 Jan 09 '20 at 15:19
-3

it's not necessary,you can do it like this:

using (StreamReader reader = File.OpenText ("file.txt"))
{
 ...
reader.Dispose();
}

it's also can clean the object

HK boy
  • 1,398
  • 11
  • 17
  • 25
zhouxu
  • 1