December 13, 2005

  • Update on the C# quirk

    It appears that the official C# specifications allow parameters and class members to take on identical names. Disambiguation is achieved through the use of the “this” reference in the method, as follows:

    class Foo
    {
    private int bar;
    public Foo(int _bar)
    {
    bar = _bar;
    }

    public Print(int bar)
    {
    System.Console.WriteLine("This is the "bar" parameter: " + bar.ToString());
    System.Console.WriteLine("This is the "bar" member: " + this.bar.ToString());
    }
    }

    Regardless, this behaviour is not what I experienced while coding my compiler. Using “bar” without the “this” reference resulted in the member instead of the parameter. Therefore, though it is officially legal for a parameter to take on the same name as a class member, I still recommend not to rely on the ambiguity resolution mechanism in Microsoft’s C# compiler. Instead, try to name your parameters differently. If you must, begin all of your parameter names with an underscore (e.g. “_bar” instead of “bar“).

    - SwordAngel

Post a Comment

Leave a Reply

Your email address will not be published. Required fields are marked *