100

With Option Strict On:

Dim theLetterA As Char = "A"

returns an error about converting the string "A" to a Char.

What is the syntax to enter a Char literal?

Mark Hurd
  • 10,665
  • 10
  • 68
  • 101
Jason Berkan
  • 8,734
  • 7
  • 29
  • 39

3 Answers3

176

A character literal is entered using a single character string suffixed with a C.

Dim theLetterA As Char = "A"C
Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
9

I would use CChar. E.g.:

 Dim theLetterA As Char = CChar("A")

Check the MSDN website https://msdn.microsoft.com/en-us/library/s2dy91zy.aspx for details on CChar.

Alan Barksdale
  • 153
  • 1
  • 6
  • Deserves more upvotes. A char ctor makes more sense than a string decorator like I've never seen before. – RJB Jul 15 '15 at 00:16
  • 20
    @RJB: You may like the syntax better, but the fact is that this is *not* a character literal. It's a statement that performs a runtime conversion from a string to a character. Not the same at all. – sstan Dec 20 '15 at 04:57
  • 2
    I agree. this is old VB code and requires the visualbasic reference. The right way is to use the convert class. Convert.ToChar("A") – Kevbo Feb 09 '16 at 22:52
  • @sstan I don't have any official statement, but it's very probable the compiler threats that sequence as character literal ("A"c) on compile time. – II ARROWS Apr 28 '17 at 13:50
  • 1
    @Kevbo - that's still a runtime action, instead of a character literal. Probably inefficient. More importantly, much more verbose. How is `Convert.ToChar("A")` a readability improvement over `"A"c`? – ToolmakerSteve Nov 13 '18 at 12:19
2

In the case of trying to get a double quote as a character literal, you'll need to use the extra quirky VB format:

Dim theQuote As Char = """"C

Or

Dim theQuote As Char = CChar("""")
andyb
  • 91
  • 1
  • 2
  • 1
    Depends on your definition of readable I suppose. I usually avoid "magic numbers" myself, and although the VB expression is quirky AF, you'd never have to pull up an ASCII table to check it was right. – andyb Sep 26 '19 at 17:30
  • I see. I don't think the ASCII code is "magic" when talking about a CHAR because that is the actual number held by the CHAR. A char is a number. If you were to inspect the memory for `theQuote` you would see `34`. – HackSlash Sep 26 '19 at 18:14