Hroatgar
Hroatgar

Reputation: 13

Passing a method as a parameter .net

I have been searching for quite a while today for an answer to my question but without success. I don't even know if its possible but I'll try my luck here.

Lets say i have this function somewhere in a class:

Public Sub sub1(i as Integer, uc as UserControl)
    ...
End Sub

And somewhwere else, in an other method i have this call:

sub1(46, new UserControl())

The problem is that i want to pass a UserControl with, lets say, a background colored in blue but it must be defined inside the method call. In other words, i want to pass an object with some properties that are modifed outside the constructor and everything must be done inside the method call. I'm thinking of something like that:

sub1(9387, {Dim uc as new UserControl()
            uc.BackColor = Color.Blue
            return uc} )

I understand that i could define a UserControl and modify it before the method call but my real situation is way more complex than that. Anyway I just want to know if it is currently possible and if yes show me some examples. In my research i found that i could do some delegate or use some "lambda" expression but I didn't find a solution that perfectly solve my question. And again, I must not write a single character of code outside the method call.

Thanks in advance!

Upvotes: 0

Views: 117

Answers (3)

nmclean
nmclean

Reputation: 7724

Immediately-invoked functions are possible in VB.NET:

Dim result As Integer = (Function() As Integer
                             Return 1
                         End Function)()

Or in your example:

sub1(9387, (Function()
                Dim uc As New UserControl()
                uc.BackColor = Color.Blue
                Return uc
            End Function)())

Upvotes: 0

OneFineDay
OneFineDay

Reputation: 9024

Like this:

sub1(9387, New UserControl With {.BackColor = Color.Blue})

Upvotes: 3

AJ.
AJ.

Reputation: 16719

If I'm understanding your question, you can simply use property initializers:

sub1(9387, New UserControl With { .BackColor = Color.Blue })

Upvotes: 0

Related Questions