What is the difference between the using statement and directive in C#?

前端 未结 5 2018
深忆病人
深忆病人 2020-12-18 05:11

this is basically a tutorial question to ask since am a beginner I would like to what is a difference between the using statement we use at start of our C# code to include a

5条回答
  •  伪装坚强ぢ
    2020-12-18 05:36

    The first (Using Directive) is to bring a namespace into scope.

    This is for example, so you can write

    StringBuilder MyStringBuilder = new StringBuilder();
    

    rather than

    System.Text.StringBuilder MyStringBuilder = new System.Text.StringBuilder();
    

    The second (Using Statement) one is for correctly using (creating and disposing) an object implementing the IDisposable interface.

    For example:

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

    Here, the Font type implements IDisposable because it uses unmanaged resources that need to be correctly disposed of when we are no-longer using the Font instance (font1).

提交回复
热议问题