Keyword

Self


Description

Self is a reference to a current main class.

Usage

Self.MemberName

Notes

When you refer to a property or method in your code without any sort of prefix, the one on the class itself (Self) is used by default.

For example, for any code contained on a window or web page, Self refers to the window or web page.

However, within an event handler of a control, you may need to access a method or property of the control. For these cases you use the Me method.

The distinction is important.

For example, say you want to move a button by changing its Left property. In the opening event handler for the button, the most obvious thing to write is this code:

Left = 100

But that does not do what you expect. Because there is no prefix, Self is implied. And Self refers to the window or web page. So the above code actually means this:

Self.Left = 100

Which sets the Left property of the window or web page and not the property of the button.

One way to get Left property of the button is to use the button name as the prefix like this:

Button1.Left = 100

This works, but it forces you to use the name of the Button to refer to the property. If you rename the button, then you will get a compile error. It also makes it more difficult to reuse the code on another button that might have a different name.

Instead, you should use the Me method:

Me.Left = 100

Because Me is used within an event handler for a control (the button in this case), it refers to the control. It is not affected should the name of the button changes and you can move this code to another button and it will work as is.

Note

When Me is used outside of a control event handler, it works the same as Self. But for clarity, you should limit your use of Me to only within event handlers.

Compatibility

All project types on all supported operating systems.

See also

Me method; Me vs. Self topic