none
Error in using statement RRS feed

  • Question

  • There's an syntax error in using statement

    using (FileInfo infoSrc = new FileInfo(FilePath))

    Error message is like following.

    'System.IO.FileInfo': type used in a using statement must be implicitly convertible to 'System.IDisposable'

    I found that the variable declared in the using statement must be of a type that implements the IDisposable interface.

    If so, isn't there any way to use non-IDisposable interface class with using statement? 


    Friday, December 1, 2017 1:01 AM

Answers

All replies

  • See the MSDN docs (and this StackOverflow post)

    https://msdn.microsoft.com/en-us/library/system.io.fileinfo%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites


    Friday, December 1, 2017 1:07 AM
    Moderator
  • Hello Jeff0803,

    The "using" statement is designed to free the object that access unmanaged resources, which object must implement the "IDisposable" interface.

    For a example that use "using" statement.

    using (Font font1 = new Font("Arial", 10.0f)) 
    {
        byte charset = font1.GdiCharSet;
    }

    It will be translated by the compiler as below.

    Font font1 = new Font("Arial", 10.0f);
      try
      {
        byte charset = font1.GdiCharSet;
      }
      finally
      {
        if (font1 != null)
          ((IDisposable)font1).Dispose();
      }

    And you will see the object must implement IDisposable interface if you are using "using". As for your case. FileInfo type you don't need to free, what you want to free is filestream or some  unmanaged type.

    Best regards,

    Neil Hu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Sunday, December 3, 2017 10:20 AM
    Moderator