Try/Finally block vs calling dispose?

前端 未结 6 1150
栀梦
栀梦 2020-12-15 11:04

Is there any difference between these two code samples and if not, why does using exist?

StreamWriter writer;
try {
    writer = new StreamWrite         


        
6条回答
  •  一整个雨季
    2020-12-15 12:01

    They're not entirely the same. The try/finally block does not protect against silly mistakes.

    StreamWriter writer = new StreamWriter(...);
    try {
      ...
      writer = new StreamWriter(...);
      ...
    } finally {
      writer.Dispose();
    }
    

    Note that only the second writer gets disposed. In contrast,

    using (StreamWriter writer = new StreamWriter(...)) {
      ...
      writer = new StreamWriter(...);
      ...
    }
    

    will give a compile-time error.

提交回复
热议问题