Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to Dispose?

I'm getting confused about all this talk about IDispose and "using" Statements. I wonder if someone can tell me if I need to use either a "using" Statement or some sort of implementation of IDispose in the following test example...

public class Main()
{
    MyFile myFile = new MyFile("c:\subdir\subdir2\testFile.txt");
    Console.Writeline("File Name: " + myFile.FileName() + "File Size: " + myFile.FileSize());
}

public class MyFile
{
    private FileInfo _fInfo;

    public MyFile(string fullFilePath)
    {
        _fInfo = new FileInfo(fullFilePath);
    }

    public string FileName()
    {
        return _fInfo.Name;
    }

    public long FileSize()
    {
        return _fInfo.Length;
    }

}
like image 454
Ann Sanderson Avatar asked Mar 19 '12 20:03

Ann Sanderson


Video Answer


2 Answers

No, your example doesn't use any resources which need disposing (it doesn't touch anything which implements IDisposable, or have any direct handles to unmanaged resources) so you don't need to implement IDisposable.

Now if you changed your class to open the file, and maintain a FileStream field referring to the open file handle, then it would make sense to implement IDisposable to close the stream.

like image 79
Jon Skeet Avatar answered Sep 19 '22 06:09

Jon Skeet


No, in the code provided I don't see any resource used that have to be disposed. So the answer is no, do not use in this code it.

like image 36
Tigran Avatar answered Sep 19 '22 06:09

Tigran