rspec/rules/S2997/rule.adoc

31 lines
924 B
Plaintext
Raw Normal View History

2020-12-23 14:59:06 +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
----
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
----
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;
}
----