Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass in an Operator

Is there any way to pass in an operator in VB.NET? I'm looking to reduce my lines of code and for two functions there is literally only an operator that is different.

For example, I have two functions, Darken and Lighten. I'd like to get to a single function with as little code as possible. The only difference are Greater Than and Less Than operators.

Function Darken(ByVal clr1 As Color, ByVal clr2 As Color) As Color
    Dim newR = If(clr2.R < clr1.R, clr2.R, clr1.R)
    Dim newG = If(clr2.G < clr1.G, clr2.G, clr1.G)
    Dim newB = If(clr2.B < clr1.B, clr2.B, clr1.B)
    Return Color.FromArgb(newR, newG, newB)
End Function
Function Lighten(ByVal clr1 As Color, ByVal clr2 As Color) As Color
    Dim newR = If(clr2.R > clr1.R, clr2.R, clr1.R)
    Dim newG = If(clr2.G > clr1.G, clr2.G, clr1.G)
    Dim newB = If(clr2.B > clr1.B, clr2.B, clr1.B)
    Return Color.FromArgb(newR, newG, newB)
End Function

What I'd like is something like (pseudo):

Function DarkenLighten(By Val Op As Operator, ByVal clr1 As Color, ByVal clr2 As Color) As Color
    Dim newR = If(clr2.R Op clr1.R, clr2.R, clr1.R)
    Dim newG = If(clr2.G Op clr1.G, clr2.G, clr1.G)
    Dim newB = If(clr2.B Op clr1.B, clr2.B, clr1.B)
    Return Color.FromArgb(newR, newG, newB)
End Function

Is this possible? I couldn't find any reference if it is possible.

like image 528
Todd Main Avatar asked Apr 14 '26 21:04

Todd Main


1 Answers

You could pass in a Func(Of Byte, Byte, Boolean) and use a lambda expression. It would still be somewhat more verbose in VB than in C#, but not too bad.

Or you could use the Func approach but have "pseudo-constants" (read-only fields) for the various delegates. Then you could just refer to GreaterThan or LessThan. I don't believe there's an easy and concise way of converting the operator itself to a delegate.

like image 148
Jon Skeet Avatar answered Apr 17 '26 13:04

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!