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
Try this:
I believe that the C# syntax is not actually assigning
Headers
to a new value (it is indeedreadonly
and cannot be assigned, even in an initializer), but rather callingHeaders.Add
on each of the items in the collection. The canonical way to do that in VB would be: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.