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

后端 未结 29 2892
有刺的猬
有刺的猬 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:43

    Just adding a little something that I was surprised did not come up. The most interesting feature of using (in my opinion) is that no mater how you exit the using block, it will always dispose the object. This includes returns and exceptions.

    using (var db = new DbContext())
    {
        if(db.State == State.Closed) throw new Exception("Database connection is closed.");
        return db.Something.ToList();
    }
    

    It doesn't matter if the exception is thrown or the list is returned. The DbContext object will always be disposed.

提交回复
热议问题