Difference between MyBase and Me

S

Sugan

Hi,

i came across custom usercontrols in VB 2005 and i'm not clear about
the difference between "Me" and "MyBase".

1. What is the difference between the two keywords in a UserControl.

2. Even if they are different, is there any harm in using it
interchangeably?

3. Where do we use "Me" and where do use "MyBase" in a UserControl.

Thanks in advance,
Sugan
 
C

Chris Dunaway

Sugan said:
i came across custom usercontrols in VB 2005 and i'm not clear about
the difference between "Me" and "MyBase".

"Me" refers to the current instance of a class. So code inside a Form
or UserControl can use Me to refer to the current instance.

"MyBase" refers to the base class, the class the the current class is
derived from. For example, Button is derived from Control. So if you
use Me you will refer to the button if you use MyBase, you will refer
to the Control class.
 
M

Marina Levit [MVP]

MyBase refers to the baseclass and it's implementation. Me refers to the
current class.

So if the base class has an overridable method Foo, and you override it in
the descendent. Then, when you say MyBase.Foo(), that will call the base
class's implementation. If you call Me.Foo(), it will call your
implementation in the descendent.

So yes, because they are different, there is harm in using them
interchangeable. You may call the wrong version of a method if you use the
wrong one, and wont' get the behavior your expect.

Use Me if you want to call an implementation in the current class. You
don't need to use it, if you just call Foo(), that is the same as Me.Foo().
If you want to specifically call the base class's version, then the only way
to do that is MyBase.Foo().

If the descendent does not override a method or property, then of course the
only implementation is in the base class, at which point it doesn't matter
which you use. But you don't want to get in the habit of having confusing
code, where it isn't clear what you are trying to call or accomplish. I
would say only use MyBase if you have overriden a method or property, but
specifically want to call the base class's version.
 
C

Chris Dunaway

Marina said:
MyBase refers to the baseclass and it's implementation. Me refers to the
current class.

Doesn't "Me" refer to the current instance of the class and "MyClass"
refer to the current class?
 
M

Marina Levit [MVP]

I meant to the current instance, my wording was off. I was just trying to
illustrate the difference between MyBase.Foo() and Me.Foo().
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top