rspec/rules/S2225/csharp/rule.adoc
2023-06-13 16:11:53 +02:00

41 lines
1.2 KiB
Plaintext

== Why is this an issue?
Calling https://learn.microsoft.com/en-us/dotnet/api/system.object.tostring[ToString()] on an object should always return a `string`. Thus, https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/how-to-override-the-tostring-method[overriding the ToString method] should never return `null`, as it breaks the method's implicit contract, and as a result the consumer's expectations.
[source,csharp,diff-id=1,diff-type=noncompliant]
----
public override string ToString ()
{
if (this.collection.Count == 0)
{
return null; // Noncompliant
}
else
{
// ...
}
}
----
A better alternative is to use the https://learn.microsoft.com/en-us/dotnet/api/system.string.empty[String.Empty] built-in field.
[source,csharp,diff-id=1,diff-type=compliant]
----
public override string ToString ()
{
if (this.collection.Count == 0)
{
return string.Empty;
}
else
{
// ...
}
}
----
include::../resources-dotnet.adoc[]
* https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/how-to-override-the-tostring-method[How to override the ToString method]
include::../rspecator.adoc[]