Use of C # using

Source: Internet
Author: User

? preface

Speaking of C # using the statement, presumably everyone is not unfamiliar, it is one of the keywords in C # . We basically write code every day to use, in fact, it is very simple.

1. first of all, tell me what the use of using is .

1) for referencing namespaces in other assemblies , for example:

using System.Collections.Generic;

2) to set an alias for a namespace or class name

1) setting aliases for namespaces

using Gen = System.Collections.Generic;

2) set alias for class name

using intlist = System.Collections.Generic. List < int >;

intlist list = New intlist();

List. ADD (1);

3) Releasing object resources

1) Releasing object resources is also one of the using common usages,C # through the . NET Framework Common Language runtime (CLR) from Memory that is used to store objects that are no longer needed.

2) The Systemmust be implemented with a class that uses a using -free object resource. The IDisposable interface, which completes the release of the resource in the Dispose () method.

2. using Basic usage

First, declare a test class

Public class usingclass : System. IDisposable

{

    public " Span lang= "en-US" style= "font-family:; Color: "> string ObjectName { get ; set ;}

public usingclass (string objname)

    {

this. ObjectName = objname;

    }

public void Dispose ()

    {

Console. WriteLine ("{0} has been destroyed ", ObjectName);

    }

}

s) declaring an object

using (usingclass UC = new usingclass(" Object " ))

{

Console. WriteLine ("using statement execution ");

}

Execution Result:

2) Declare multiple objects at the same time

using (UsingclassUCA =New Usingclass("object A " ), UCB =New Usingclass("object B " ), UCC =New Usingclass("object C " ))

{

Console. WriteLine ("using statement execution ");

}

Execution Result:

3) new object (of course, this usage is of no practical significance)

using (new usingclass(" object "))

{

Console. WriteLine ("using statement execution ");

}

Execution Result:

Use of C # using

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.