skip to Main Content

Question for the VB experts here!

I have the following code in C#:

public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
    HttpRequestMessageProperty httpRequestProperty = new HttpRequestMessageProperty()
    {
        Headers =
        {
            "test", "test"
        }
    };
    request.Properties.Add(HttpRequestMessageProperty.Name, httpRequestProperty);
    return null;
}

I have tried to turn this into VB code like this:

Public Function BeforeSendRequest(ByRef request As Message, ByVal channel As IClientChannel) As Object
    Dim httpRequestProperty As HttpRequestMessageProperty = New HttpRequestMessageProperty() With {
        .Headers = {
            {"test", "test"}
        }
    }
    request.Properties.Add(HttpRequestMessageProperty.Name, httpRequestProperty)
    Return Nothing
End Function

To my understanding this should be correct, but Visual Studio is complaining that Headers is a readonly property. This though should not be a problem when I am initializing a class. Any idea why this is the case? To my understanding C# and VB should be similar that I should be able to do this. If for some reason this isn’t possible in VB, how can I achieve the same as in my C# code?

2

Answers


  1. Try this:

    Public Function BeforeSendRequest(ByRef request As Message, ByVal channel As IClientChannel) As Object
        Dim headers As New WebHeaderCollection()
        headers.Add("test", "test")
    
        Dim httpRequestProperty As New HttpRequestMessageProperty() With {
            .Headers = headers
        }
    
        request.Properties.Add(HttpRequestMessageProperty.Name, httpRequestProperty)
        Return Nothing
    End Function
    
    Login or Signup to reply.
  2. I believe that the C# syntax is not actually assigning Headers to a new value (it is indeed readonly and cannot be assigned, even in an initializer), but rather calling Headers.Add on each of the items in the collection. The canonical way to do that in VB would be:

    Dim httpRequestProperty As HttpRequestMessageProperty = New HttpRequestMessageProperty()
    httpRequestProperty.Headers.Add("test", "test")
    
    request.Properties.Add(HttpRequestMessageProperty.Name, httpRequestProperty)
    
    

    There may be a slicker VB syntax to inline the adds, but I would start with something that works and then decide if it’s worth the time and effort to inline it.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search