-1
var baseAddress = new Uri("http://www.aaa.com");
    var cookieContainer = new CookieContainer();
    using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
    using (var client = new HttpClient(handler){ BaseAddress = baseAddress })
{}

I tried to convert this code with the Developer Fusion tool to VB.NET but was not successful.

Dim baseAddress = New Uri("http://www.aaa.com")
Dim cookieContainer = New CookieContainer()
Using handler = New HttpClientHandler() With { _
    Key .CookieContainer = cookieContainer _
}
    Using client = New HttpClient(handler) With { _
        Key .BaseAddress = baseAddress _
    }
    End Using
End Using

an error occured "key . "

What is the VB.NET equivalent of this code (using with statement)?

Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38
Pisagor
  • 147
  • 1
  • 2
  • 16
  • Try closing the gap between Key and the dot – JsonStatham Jun 29 '15 at 08:34
  • no , i tried this before but not working...(Error 2 Name of field or property being initialized in an object initializer must start with '.'. – Pisagor Jun 29 '15 at 08:35
  • ok i tried delete only "Key" word and it run! Key .CookieContainer = cookieContainer--> .CookieContainer = cookieContainer – Pisagor Jun 29 '15 at 08:38

2 Answers2

3

Just remove the Key word

Using handler = New HttpClientHandler() With { _
    .CookieContainer = cookieContainer _
}
    Using client = New HttpClient(handler) With { _
        .BaseAddress = baseAddress _
    }
    End Using
End Using
2

I learnt something new (Object Initializers: Named and Anonymous Types) from Kilanny's answer; here's how I refactored the converted code:

    Dim baseAddress = New Uri("http://www.aaa.com")
    Dim cookieContainer = New Net.CookieContainer()
    Using handler As New HttpClientHandler
        With handler
            .CookieContainer = cookieContainer
            Using client As New HttpClient(handler)
                With client
                    .BaseAddress = baseAddress
                End With
            End Using
        End With
    End Using
  1. Object Initializers: Named and Anonymous Types (Visual Basic)
  2. Using Statement (Visual Basic)
  3. With...End With Statement (Visual Basic)
SimplyInk
  • 5,832
  • 1
  • 18
  • 27