'XLabel': member names cannot be the same as their enclosing type

BenTam-3003 686 Reputation points
2022-06-30T14:49:37.82+00:00

Dear All,

What does the error message "'XLabel': member names cannot be the same as their enclosing type" mean?

216633-xlabel.gif

Developer technologies | C#
{count} votes

1 answer

Sort by: Most helpful
  1. Michael Taylor 60,341 Reputation points
    2022-06-30T15:31:47.123+00:00

    This is a standard C# rule. You are not allowed to use the same name for a type and a member within that type.

       public class XLabel  
       {  
          public string XLabel { get; set; } //Compiler error  
       }  
    

    Here you have a member with the same name as its type and therefore the compiler will not be able to figure out which one to use when you try to reference it in the code.

       public void Foo ()  
       {  
          //Should this be showing/using members of the type XLabel that are static  
          // Or should this be the members of the property XLabel?  
          XLabel.  
       }  
    

    So the language forbids it. What does that have to do with your markup. x:Name is used by the designer to create a backing field that is automatically tied to that element. So this:

       <TextBox x:Name="myText" />  
    

    Generates this:

       private TextBox myText;  
    

    So if you set x:Name to the same identifier as the type that contains it then you are creating a member with the same name as its owning type, hence the error. You should set the name of a control to the field name you want to back it. Standard practice is to use lower case (and often underscores) for field names to avoid conflicts. So I would recommend something like this:

       <UserControl x:Name="myControl" />  
    

    In your case the name seems questionable anyway because the user control inside your XLabel isn't probably XLabel but rather a child control that is part of your XLabel parent control. So use an appropriate name here.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.