You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This rule flags `using` statements that use fields, member access expressions, or local variables, which can lead to double disposal or ownership issues.
16
+
17
+
## Reason
18
+
19
+
Using statements with fields or variables can be problematic because they may dispose objects that are already being managed elsewhere, potentially causing:
20
+
21
+
- Double disposal exceptions when the object is disposed both by the using statement and by other code
22
+
- Access to disposed objects if the field/variable is used after the using block
23
+
- Unclear ownership semantics where multiple parts of code think they own the object
24
+
25
+
## How to fix violations
26
+
27
+
Replace problematic using patterns with safer alternatives:
28
+
29
+
- Create new objects directly in the using statement
30
+
- Call methods that return disposable objects
31
+
- Use parameters instead of fields when possible
32
+
- Consider refactoring the design to have clearer ownership semantics
33
+
34
+
## Examples
35
+
36
+
### Incorrect
37
+
38
+
```csharp
39
+
classBadExample
40
+
{
41
+
privateStream_stream=newMemoryStream();
42
+
43
+
publicvoidBadMethod()
44
+
{
45
+
// Direct field usage - may lead to double disposal
46
+
using (_stream)
47
+
{
48
+
// Do something
49
+
}
50
+
51
+
// Field assignment to using variable
52
+
using (varlocalStream=_stream)
53
+
{
54
+
// Do something
55
+
}
56
+
57
+
// Member access expression
58
+
using (this.Stream)
59
+
{
60
+
// Do something
61
+
}
62
+
63
+
// Local variable reuse
64
+
StreamexistingStream=newMemoryStream();
65
+
using (varlocalStream=existingStream)
66
+
{
67
+
// Do something
68
+
}
69
+
}
70
+
}
71
+
```
72
+
73
+
### Correct
74
+
75
+
```csharp
76
+
classGoodExample
77
+
{
78
+
publicvoidGoodMethod(StreaminputParameter)
79
+
{
80
+
// Create new object directly - safe
81
+
using (varstream=newMemoryStream())
82
+
{
83
+
// Do something
84
+
}
85
+
86
+
// Method call that returns disposable - safe
87
+
using (varstream=CreateStream())
88
+
{
89
+
// Do something
90
+
}
91
+
92
+
// Using parameter - safe (caller owns the object)
0 commit comments