Examples of errors detected by the V3108 diagnostic
V3108. It is not recommended to return null or throw exceptions from 'ToString()' method.
Orchard CMS
V3108 It is not recommended to return 'null' from 'ToString()' method. SnippetHtmlExtensions.cs 60
public override string ToString() {
....
return null;
}
FastReport
V3108 It is not recommended to return 'null' from 'ToString()' method. Variant.cs 1519
public override string ToString() {
if (_value == null) return null;
return this.String;
}
.NET Core Libraries (CoreFX)
V3108 It is not recommended to return 'null' from 'ToString()' method. StringAttributeCollection.cs 57
public override string ToString()
{
if (Count <= 0) return null; // <=
StringBuilder sb = new StringBuilder();
foreach (string str in this)
{
....
sb.Append(str.Trim());
sb.Append(',');
}
if (sb.Length > 0) sb.Length = sb.Length - 1;
return sb.Length == 0 ? null : sb.ToString(); // <=
}
Similar errors can be found in some other places:
- V3108 It is not recommended to return 'null' from 'ToString()' method. StringAttributeCollection.cs 71
.NET Core Libraries (CoreFX)
V3108 It is not recommended to return 'null' from 'ToString()' method. RepeatBehavior.cs 113
public struct RepeatBehavior : IFormattable
{
....
public override string ToString()
{
return InternalToString(null, null); // <=
}
....
}
internal string InternalToString(string format, IFormatProvider formatProvider)
{
switch (_Type)
{
case RepeatBehaviorType.Forever:
return "Forever";
case RepeatBehaviorType.Count:
StringBuilder sb = new StringBuilder();
sb.AppendFormat(
formatProvider,
"{0:" + format + "}x",
_Count);
return sb.ToString();
case RepeatBehaviorType.Duration:
return _Duration.ToString();
default:
return null; // <=
}
}
.NET Core Libraries (CoreFX)
V3108 It is not recommended to return 'null' from 'ToString()' method. JsonElement.cs 1460
public override string ToString()
{
switch (TokenType)
{
....
case JsonTokenType.String:
return GetString();
....
}
}
public string GetString()
{
....
return _parent.GetString(_idx, JsonTokenType.String);
}
internal string GetString(int index, JsonTokenType expectedType)
{
....
if (tokenType == JsonTokenType.Null)
{
return null;
}
....
}
ShareX
V3108 It is not recommended to return 'null' from 'ToString()' method. Logger.cs 167
public override string ToString()
{
lock (loggerLock)
{
if (sbMessages != null && sbMessages.Length > 0)
{
return sbMessages.ToString();
}
return null;
}
}
BTCPay Server
V3108 It is not recommended to return 'null' from 'ToString()' method. BTCPayServer\Controllers\UILNURLController.cs 364
public class LightningAddressSettings
{
....
public override string ToString()
{
return null;
}
....
}