views:

66

answers:

1

Curious situation:

public class MyTextBox : TextBox 
{        
    // I want use the same height for all MyTextBoxes 
    public new static int Height; 
}

    public Form1()
    {
        InitializeComponent();

        MyTextBox mtb1 = new MyTextBox();
        MyTextBox mtb2 = new MyTextBox();

        mtb1.Multiline = true;
        mtb2.Multiline = true;

        mtb1.Location = new Point(50, 100);
        mtb2.Location = new Point(200, 100);

        mtb1.Size = new Size(50, 50);
        mtb2.Size = new Size(150, 150);

        Controls.Add(mtb1);
        Controls.Add(mtb2);

        mtb1.Text = mtb1.Height;
        mtb2.Text = mtb2.Height; 
        // Error 1 Member 'WindowsFormsApplication9.MyTextBox.Height' 
        // cannot be accessed with an instance reference; 
        // qualify it with a type name instead
    }

The same thing in VB.NET

Public Class MyTextBox
  Inherits TextBox
  Public Shared Shadows Height As Integer
End Class

mtb1.Text = mtb1.Height ' Text will be "0" '
'Warning 1   Access of shared member, constant member, enum member or nested ' 
' type through an instance; qualifying expression will not be evaluated.

Questions:

  1. Now, ask myself if this method couldn't be used to hide the public members in the inherited classes. Sometimes this can be useful...
  2. How can I use same Height for all members?
+1  A: 

When would it be useful? I really don't think it's a good idea to hide members in this way. It's just going to cause a maintenance nightmare - when you see "Height" you can't easily tell which member it's really referring to.

IMO, "new" should only be used as a last act of desperation, usually if a base class has introduced a member which clashes with one of your existing ones. It shouldn't be used as a way of deliberately avoiding normal OO design principles.

Jon Skeet
ok, what about the same height for all textboxes? Or I should rename the field?
serhio
@serhio: Definitely rename the field - if indeed you need a field in the first place.
Jon Skeet