Implement IDisposable with Empty Dispose for Readability

I like the using () {} statement for its control over the scope and for readability. You can not only create objects, use them and carefully dispose of them, but you can also use them like this:

Suppose myInstance is an instance of MyClass from another place in the code - that is, a method parameter or something

using (var t = myInstance) {
    t.Foo= "Hello";
    t.Bar= "World";
    ...
}

MyClass definition:

public class MyClass : IDisposable
{
   public string Foo {get; set;}
   public string Bar {get; set;}
   ...

   public void Dispose() {}
}

This makes the code tidier and easier to read (I feel) and of course easier to type. However, to use this widely, you need to implement IDisposable. In this case, there is no need for MyClass to actually process anything in Dispose, so its empty.

My question is, is there a drawback to using IDisposable this way?

, , , IDispose ( ).

EDIT:

, , , . using - , , . , . , , , null, , . ?

+3
6

IDisposable, , , . , , . IDisposable, . .

:

{
  var _ = instance;
  _.Foo = "Hello"; 
  _.Bar = "World"; 
}

:

instance.With(_ => {
  _.Foo = "Hello";
  _.Bar = "World"; 
});

...

public static class WithExtensions {
  public static void With<T>(this T instance, Action<T> action) {
    action(instance);
  }
}

, , , .

, . , (, Nemerle). # ​​, using , . lambdas , , With. , "" .

+5

, using.

:

{ var t = myInstance;
    t.Foo= "Hello";
    t.Bar= "World";
    ...
}

.

IDisposable .
IDisposable , , .
, .

+5

, try/finally.

+2

(ab) using, , - . , (, , ​​ ):

public void WorkWithMyInstance(MyInstance t)
{
  t.Foo= "Hello";
  t.Bar= "World";
  ...
}
+1

, . :

The main use of this interface is to free unmanaged resources.

If you just use IDisposableit so that you can wrap it in an instruction using, I think this gives the wrong impression to the users of your classes. They can interpret this code as more than what it really does.

I think that unintended consequences will be confusion.

0
source

Can you also use this feature?

var myclass = new MyClass
{
MyProperty1 = "Property1",
MyProperty2 = "Property2",
};
0
source

All Articles