Search code examples
c#vb.netinitializationdotnet-httpclientcode-conversion

Converting C# to VB: New... With {Read-Only Property}


In trying to convert the following C# code from a tutorial (by hand, since cross-compilers I have tried don't seem to be able to do this):

httpClient = new HttpClient(unrelated args)
{
    DefaultRequestHeaders = 
    { 
        Accept = { MediaTypeWithQualityHeaderValue.Parse("text/json") } 
    }
}

The closest I have been able to get it is:

Dim httpClient As New HttpClient(unrelated args) With
{
    .DefaultRequestHeaders [=[New HttpRequestHeaders]] [With] 
    {
        .Accept = {MediaTypeWithQualityHeaderValue.Parse("text/json") 
    }
}

(where I have tried various combinations of the values in brackets)

No matter what I try, the best I can get is the error

Property DefaultRequestHeaders is ReadOnly.

I have confirmed that .DefaultRequestHeaders and .Accept are ReadOnly in both VB and C#. Apparently C# is able to write to ReadOnly properties at initialization? Is VB not able to do this as well, or is there some nuance of syntax I am missing to be able to do this? Failing being able to set this at initialization, some other way to set the actual value would presumably work; unfortunately, I don't see a constructor that exposes it, so I don't see any other way to accomplish this, though I would also welcome any suggestion along those lines.


Solution

  • I have confirmed that .DefaultRequestHeaders and .Accept are ReadOnly in both VB and C#. Apparently C# is able to write to ReadOnly properties at initialization?

    Nope. C# cannot write to read-only properties any more than VB can. But read-only properties can return an object that can be written to.

    What you are looking at are C# collection initializers. They allow you to create collections in one line without having to call Add again and again.

    VB also has collection initialzers, but the syntax is very different. That said, it is not 100% necessary to do it that way, especially if you are only adding a single item to the collection.

    Dim httpClient As New HttpClient(args As unrelated) 'Assuming unrelated is a type (not sure)
    httpClient.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("text/json"))