Total .NET Analyzer Rule Documentation  

VariableGlobalConflict Rule

Avoid using the same name for classes and fields.

Remarks

Avoid having identical variable and class names. Although the compiler allows classes and variables to be named identically, doing this creates code that is difficult to understand and maintain. For example, the following code contains a variable with the same name as the class:


' VB
Public Class Customer
Sub CreateCustomerID()
Dim Customer As String
Customer = "John Doe"
End Sub
End Class

// C#
class Customer
{
public static void CreateCustomerID()
{
string Customer;
Customer = "John Doe";
}
}


In Visual Basic, variables can also conflict with Module declarations. For example:

Public Class Class1
Sub test()
Dim CustomerID As Integer
End Sub
End Class

Public Module MainMod
Dim CustomerID As Integer
End Module


Even with very short examples, identical class and field names create very confusing code.

Resolution

To make the code easier to understand, rename the field or the class to be unique. For instance, the code example above could be revised to the following:

' VB
Public Class CustomerInformation
Dim CustomerName As String
Sub CreateCustomerID()
CustomerName = "John Doe"
End Sub
End Class

// C#
class CustomerInformation
{
public static void CreateCustomerID()
{
string CustomerName;
Customer = "John Doe";
}
}

See Also