purechaos12
purechaos12

Reputation: 32

Add a constructor to an existing structure

Is there a way to add a constructor to the Rectangle Structure?

Is this even possible without inheriting from the class?

Upvotes: 0

Views: 463

Answers (2)

Salvatore Previti
Salvatore Previti

Reputation: 9050

There is no way to add an external constructor to a structure.

The thing you can do is to declare somewhere a static class with the function you need that returns a rectangle.

Public Class Utilities

    Public Shared Function GetMySpecialRectangle(ByVal x As Integer) As Rectangle
        Return New Rectangle(x, 0, 100, 100)
    End Function

End Class

And to use it...

Dim r As Rectangle = Utilities.GetMySpecialRectangle(19)

In some specific circumstance you can also use Extension methods. If you never heard about that, there is an example.

Module MyExtensions

    <Runtime.CompilerServices.Extension()>
    Public Function ToMySpecialRectangle(ByVal x As Integer) As Rectangle
        Return New Rectangle(x, 0, 100, 100)
    End Function

End Module

And to use it...

Dim x As Integer = 0
Dim rect As Rectangle = x.ToMySpecialRectangle()

This actually adds an "extension" method to class Integer, an extension method mimics a class method, but is a just a static module method called with a different syntax.

It just means that each time you do integerValue.ToMySpecialRectangle() you are calling the module function ToMySpecialRectangle(integerValue) instead, just syntactic sugar.

There is however nothing like that about constructors.

Upvotes: 2

Milan Jaric
Milan Jaric

Reputation: 5646

If I'm not wrong Rectangle is NotInheritable Class Rectangle which inherits Shape and you can not inherit NotInheritable

Upvotes: 0

Related Questions