Click here to Skip to main content
15,890,512 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I don't know how exactly to put this in words, Using a color as an example:

I know how to write basic <Extension()> methods:
VB
<Extension()>
Public Function GetRedValue(byval c as Color) as byte
    Return c.R
End Function


I could use:
VB
Dim Col as Color = Color.LimeGreen
Label1.Text = Col.GetRedValue().ToString


And it would return the value of Color.R as expected.

What I am trying to figure out is how to run a method without having an instance of color already created in order to return a new instance of that object.

It seems like the Color structure can inherently do it. When you create a new color you can use a predefined color or define the object like:
VB
Dim col as Color = Color.FromARGB(Alpha, Red, Green, Blue)

without having an instance already created.

How to I create my own method that work in the same fashion
Example:
VB
<Extension()>
Public Function FromHSV(byval c as Color, Hue as Single, Saturation as Single, Value as Single) as Color
    Dim ReturnColor as Color = ConvertToRGB(Hue, Saturation, Value) '<<== My Own Routine to return a color
Return ReturnColor
End Function


So that I may use it like:
VB
Dim Col as Color = Color.FromHSV(0.5, 0.2, 1.0)


or even
VB
Dim Col as Color = Color.MyCustomColor


I'm hoping I am making myself clear as I was not sure of the correct terminology for what I am trying to accomplish.
Any help is appreciated, Thank You!

What I have tried:

I thought the Shared parameter would work, but you can't use Shared within a module and you can't use <Extension()> within a class.

I have searched and found nothing that helps.
Posted
Updated 3-Mar-16 23:41pm

1 solution

Extension methods make it possible to write a method that can be called as if it were an instance method of the existing type.

Extension methods can only be used as instance methods on the type. You're trying to define a new Shared method on the type, which isn't possible.

Instead, you'll need to use your module name to call your function:
VB.NET
Public Module ColorExtensions
    Public Function FromHSV(ByVal hue As Single, ByVal saturation As Single, ByVal value As Single) As Color
        ...
    End Function
End Module
...
Dim col As Color = ColorExtensions.FromHSV(0.5, 0.2, 1.0)
 
Share this answer
 
Comments
FatzBomb 4-Mar-16 6:38am    
I was afraid of that, not a big deal but less seamless. Either way I can make it work. You saved me many more hours of searching, thank you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900