The following example shows a class that ignores the result of calling String.Trim.
[C#]
using System;
namespace Samples
{
public class Book
{
private readonly string _Title;
public Book(string title)
{
if (title != null)
{
// Violates this rule
title.Trim();
}
_Title = title;
}
public string Title
{
get { return _Title; }
}
}
}
[Visual Basic]
Imports System
Namespace Samples
Public Class Book
Private ReadOnly _Title As String
Public Sub New(ByVal title As String)
If title IsNot Nothing Then
' Violates this rule
title.Trim()
End If
_Title = title
End Sub
Public ReadOnly Property Title() As String
Get
Return _Title
End Get
End Property
End Class
End Namespace
[C++]
using namespace System;
namespace Samples
{
public ref class Book
{
private:
initonly String^ _Title;
public:
Book(String^ title)
{
if (title != nullptr)
{
// Violates this rule
title->Trim();
}
_Title = title;
}
property String^ Title
{
String^ get() { return _Title; }
}
};
}
The following example fixes the above violation by assigning the result of String.Trim back to the variable it was called on.
[C#]
using System;
namespace Samples
{
public class Book
{
private readonly string _Title;
public Book(string title)
{
if (title != null)
{
title = title.Trim();
}
_Title = title;
}
public string Title
{
get { return _Title; }
}
}
}
[Visual Basic]
Imports System
Namespace Samples
Public Class Book
Private ReadOnly _Title As String
Public Sub New(ByVal title As String)
If title IsNot Nothing Then
title = title.Trim()
End If
_Title = title
End Sub
Public ReadOnly Property Title() As String
Get
Return _Title
End Get
End Property
End Class
End Namespace
[C++]
using namespace System;
namespace Samples
{
public ref class Book
{
private:
initonly String^ _Title;
public:
Book(String^ title)
{
if (title != nullptr)
{
title = title->Trim();
}
_Title = title;
}
property String^ Title
{
String^ get() { return _Title; }
}
};
}