Incorrect suggestion to "Convert to 'using' declaration Follow
(Using Resharper version 2020.1.4)
Consider the following console application:
using System;
using System.Runtime.Serialization;
using System.Text;
using System.Xml;
namespace ConsoleApp1
{
class Program
{
static void Main()
{
Console.WriteLine(Serialise("test"));
}
public static string Serialise(string data)
{
var serialiser = new DataContractSerializer(typeof(string));
var result = new StringBuilder();
using (var writer = XmlWriter.Create(result))
{
serialiser.WriteObject(writer, data);
}
return result.ToString();
}
}
}
The output of this is:
<?xml version="1.0" encoding="utf-16"?><string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">test</string>
Resharper suggests converting the `using` to a using declaration, like so:
public static string Serialise(string data)
{
var serialiser = new DataContractSerializer(typeof(string));
var result = new StringBuilder();
using var writer = XmlWriter.Create(result);
serialiser.WriteObject(writer, data);
return result.ToString();
}
If you follow this advice then the code is broken - the return value from `Serialize()` will now be an empty string.
Is this a bug? Or just something to watch out for? (If the latter, then it makes the "Convert to 'using' declaration in file|project|solution" options too dangerous to use effectively.)
Please sign in to leave a comment.