rspec/rules/S2997/rule.adoc

35 lines
1004 B
Plaintext
Raw Normal View History

== Why is this an issue?
2021-01-27 13:42:22 +01:00
Typically you want to use ``++using++`` to create a local ``++IDisposable++`` variable; it will trigger disposal of the object when control passes out of the block's scope. The exception to this rule is when your method returns that ``++IDisposable++``. In that case ``++using++`` disposes of the object before the caller can make use of it, likely causing exceptions at runtime. So you should either remove ``++using++`` or avoid returning the ``++IDisposable++``.
2020-06-30 12:48:07 +02:00
=== Noncompliant code example
2020-06-30 12:48:07 +02:00
2022-02-04 17:28:24 +01:00
[source,text]
2020-06-30 12:48:07 +02:00
----
public FileStream WriteToFile(string path, string text)
{
using (var fs = File.Create(path)) // Noncompliant
{
var bytes = Encoding.UTF8.GetBytes(text);
fs.Write(bytes, 0, bytes.Length);
return fs;
}
}
----
=== Compliant solution
2020-06-30 12:48:07 +02:00
2022-02-04 17:28:24 +01:00
[source,text]
2020-06-30 12:48:07 +02:00
----
public FileStream WriteToFile(string path, string text)
{
var fs = File.Create(path);
var bytes = Encoding.UTF8.GetBytes(text);
fs.Write(bytes, 0, bytes.Length);
return fs;
}
----