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

前端 未结 5 2013
深忆病人
深忆病人 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).

    0 讨论(0)
  • 2020-12-18 05:36

    I'm sure someone will spend a great deal of time answering what amounts to a Google search but here are a couple of links to get you started.

    The using Statement (C# Reference) ensures that Dispose is called even if an exception occurs while you are calling methods on the object.

    To allow the use of types in a namespace so that you do not have to qualify the use of a type in that namespace use using Directive (C# Reference).

    You may find that MSDN is a great resource to spend some time browsing.

    0 讨论(0)
  • 2020-12-18 05:43

    using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))

    This using disposes the adapter object automatically once the control leaves the using block.

    This is equivalent to the call

    SqlDataAdapter adapter = new SqlDataAdapter(cmd)
    adapter.dispose();
    

    See official documentation on this: http://msdn.microsoft.com/en-us/library/yh598w02(v=vs.71).aspx

    0 讨论(0)
  • 2020-12-18 05:54

    They are about as different as you can get.

    The first shows intent to use things within a namespace.

    The second takes a reference to a disposable object and ensures it is disposed, no matter what happens (like implementing try/finally)

    0 讨论(0)
  • 2020-12-18 05:59

    The first allows you to use types that are not defined in your code (tells the compiler where to find the code it needs to reference. REF: http://msdn.microsoft.com/en-us/library/sf0df423(v=VS.100).aspx

    The second using makes sure that the memory is released upon the end of the code block, or in the case of an exception. REF: http://msdn.microsoft.com/en-us/library/yh598w02.aspx

    Please see the links above for detailed documentation on each.

    0 讨论(0)
提交回复
热议问题