What are the uses of “using” in C#?

后端 未结 29 2890
有刺的猬
有刺的猬 2020-11-21 07:31

User kokos answered the wonderful Hidden Features of C# question by mentioning the using keyword. Can you elaborate on that? What are the uses of

29条回答
  •  爱一瞬间的悲伤
    2020-11-21 07:57

    Another example of a reasonable use in which the object is immediately disposed:

    using (IDataReader myReader = DataFunctions.ExecuteReader(CommandType.Text, sql.ToString(), dp.Parameters, myConnectionString)) 
    {
        while (myReader.Read()) 
        {
            MyObject theObject = new MyObject();
            theObject.PublicProperty = myReader.GetString(0);
            myCollection.Add(theObject);
        }
    }
    

提交回复
热议问题