The following example shows a constructor that incorrectly instantiates an instance of the ArgumentNullException type.
[C#]
using System;
namespace Samples
{
public class Book
{
private readonly string _Title;
public Book(string title)
{
// Violates this rule (constructor arguments are switched)
if (title == null)
throw new ArgumentNullException("title cannot be a null reference (Nothing in Visual Basic)", "title");
_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)
' Violates this rule (constructor arguments are switched)
If (title Is Nothing) Then Throw New ArgumentNullException("title cannot be a null reference (Nothing in Visual Basic)", "title")
_Title = title
End Sub
Public ReadOnly Property Title()
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)
{
// Violates this rule (constructor arguments are switched)
if (title == nullptr)
throw gcnew ArgumentNullException("title cannot be a null reference (Nothing in Visual Basic)", "title");
_Title = title;
}
property String^ Title
{
String^ get()
{
return _Title;
}
}
};
}
The following example fixes the above violation by switching the constructor arguments.
[C#]
using System;
namespace Samples
{
public class Book
{
private readonly string _Title;
public Book(string title)
{
if (title == null)
throw new ArgumentNullException("title", "title cannot be a null reference (Nothing in Visual Basic)");
_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 Is Nothing) Then Throw New ArgumentNullException("title", "title cannot be a null reference (Nothing in Visual Basic)")
_Title = title
End Sub
Public ReadOnly Property Title()
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)
throw gcnew ArgumentNullException("title", "title cannot be a null reference (Nothing in Visual Basic)");
_Title = title;
}
property String^ Title
{
String^ get()
{
return _Title;
}
}
};
}