VB.NET: Add additional functions to a class

class, customization, vb.net

Solution

You could

- extend the class (like `Rectangle`) via extension methods

- create a custom class that holds a `Rectangle` instance(has a rectangle) and add additional properties and methods

Note that you can't inherit from `Rectangle` to extend it's functionality since it is not a `Class` but a `Structure`.

Here's a simple extension:

Module RectangleExtensions

    <System.Runtime.CompilerServices.Extension()> _
    Public Sub Move(rectangle As Rectangle, x As Int32, y As Int32)
        rectangle.Location = New Point(x, y)
    End Sub

End Module

which you can use as if it were an existing method in `Rectangle`

Dim rec = New Rectangle(New Point(100, 100), New Size(50, 50))
rec.move(100, 200)

Problem

the "Rectangle" class does not expose all the functions that I would need to manipulate the rectangle. For example, I often want to change the ".Bottom" value only. None of the existing functions allow me to do so, and I find myself creating a new rectangle to do what I need. This brings me to a general question: Is it possible to add additional functions to a class in the framework that are then available in my entire project?

Original source