1

A co-worker of mine and I both do programming. He has made a class in C# and I am working on converting it to VB.NET. I got the full class converted except for a single line, and at this point I cannot figure it out so thought a fresh set of eyes maybe able to find my error.

Original C# code

using (var client = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate })) 

Converted VB.NET code

Using client = New HttpClient(New HttpClientHandler With {Key .AutomaticDecompression = DecompressionMethods.GZip Or DecompressionMethods.Deflate})

Error Name of field or Property being initialized in an object initialize must start with '.'.

Error is located under the 'Key'

Last note: I used a dreaded code-converter for most of it, so I am unsure where 'key' came from.

Ry-
  • 218,210
  • 55
  • 464
  • 476
dwb
  • 475
  • 6
  • 31

2 Answers2

5

There are two concepts which have similar syntax but different semantics:

Anonymous Types

C#: new { A = 1, B = 2 }

VB: New With { Key .A = 1, Key .B = 2 }

Here, VB also allows you to add mutable (non-key) properties, which C# does not support:

New With { Key .A = 1, Key .B = 2, .SomeMutableProperty = 3 }

Hence, the Key keyword is important here.

Object Initializers for Named Types

C#: new MyClass { A = 1, B = 2 }

VB: New MyClass With { .A = 1, .B = 2 }

Here, existing properties of MyClass are set, so the Key keyword is irrelevant, and, thus, not allowed.


Apparently, your C# -> VB converter thought that this was an anonymous type, although it was an object initializer. Remove the Key keyword and send a bug report to the converter's developer.

Community
  • 1
  • 1
Heinzi
  • 167,459
  • 57
  • 363
  • 519
2

Not sure where the Key has come from.

Running this through Instant VB gives the following, so it would concur with my thought that the Key is not required:

Option Infer On

Using client = New HttpClient(New HttpClientHandler With {.AutomaticDecompression = DecompressionMethods.GZip Or DecompressionMethods.Deflate})
Matt Wilko
  • 26,994
  • 10
  • 93
  • 143
  • And thats why I needed a fresh set of eyes lol... Awesome that fixed it. I will mark as answered when the timer runs out. – dwb Jan 27 '16 at 17:00