GOTCHA 32 Mixing case between class members breaks interoperability


GOTCHA #32 Mixing case between class members breaks interoperability

Do not create properties or methods that differ only by case. C# (like C++ and Java) is case-sensitive. VB.NET (like VB6) is not. So how would VB.NET handle a C# class that has two different properties with the same name (i.e., their spelling differed only by case)? This is illustrated in Example 4-5.

Example 4-5. Mixing the case

C# and VB.NET (DifferInCase)

   //SomeClass.cs part of CSLib.dll using System;   namespace CSLib {     public class SomeClass     {         public int Value1         {             get { return 1; }         }           public int value1         {             get { return 2; }         }     } } 

Here you have a C# class SomeClass with two properties, Value1 and value1. The C# compiler has no objection to this. Now let's write a VB.NET class that uses the above class, as in Example 4-6.

Example 4-6. Using C# class with mixed-case members

C# and VB.NET (DifferInCase)

   'TestModule.vb part of VBUser.exe   Module TestModule       Sub Main()         Dim obj As New CSLib.SomeClass           Dim val As Integer           val = obj.Value1     End Sub   End Module 

When you compile, you get the error shown in Figure 4-4.

Figure 4-4. Error compiling code in Example 4-6


In .NET Version 1.0, this compilation error did not appear. Instead the first property with that name was used. In this case, Value1 would have been used instead of value1.


How does this differ in .NET 2.0 Beta 1? There is no compilation error; the behavior is the same as in .NET version 1.0.

These two properties can be accessed in C# without any problem. The C# compiler resolves the names properly. The VB.NET compiler, however, gets confused about this "overloading." Incidentally, you can use reflection in VB.NET to access these two properties, because the CLR uses case-sensitive matching to determine the members.

IN A NUTSHELL

Do not write properties, methods, or fields whose names differ only by case. This breaks interoperability.

SEE ALSO

Gotcha #31, "Optional parameters break interoperability," Gotcha #33, "Name collision with keywords breaks interoperability," and Gotcha #34, "Defining an array isn't consistent."



    .NET Gotachas
    .NET Gotachas
    ISBN: N/A
    EAN: N/A
    Year: 2005
    Pages: 126

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net