Deborah's Developer MindScape






         Tips and Techniques for Web and .NET developers.

February 22, 2010

Setting a Char Value

Filed under: C#,VB.NET @ 3:12 pm

Strings are a .NET data type that we use every day. But char, not so much.

char is a built-in .Net data type used to declare a Unicode character. Unicode characters are 16-bit and can represent any character used in any known written language.

A char value is defined using a character literal, decimal value, hexadecimal value, or Unicode.

In C#:

// Define a D
// Character literal
char myD  = ‘D’;
// Decimal
char myD2 = (char)68;
// Hexadecimal
char myD3 = ‘\x0044’;
// Unicode
char myD4 = ‘\u0044’;

Console.WriteLine(myD);
Console.WriteLine(myD2);
Console.WriteLine(myD3);
Console.WriteLine(myD4);

Notice the single quotes in the first example. Using single quotes in C# defines a character literal. Using double-quotes defines a string literal.

In VB:

‘ Define a D
‘ Character literal
Dim myD As Char = "D"c
‘ Decimal
Dim myD2 As Char = ChrW(68)
‘ Hexadecimal
Dim myD3 As Char = ChrW(&H44)
‘ Unicode
Dim myD4 As Char = ChrW(&H44)

Console.WriteLine(myD)
Console.WriteLine(myD2)
Console.WriteLine(myD3)
Console.WriteLine(myD4)

Notice the small “c” after the string. Using the “c” in VB defines a character literal.

The above code example results in displaying “D” four times.

Use this technique any time you need to use char data in your application.

Enjoy!

RSS feed for comments on this post. TrackBack URI

Leave a comment

© 2019 Deborah's Developer MindScape   Provided by WPMU DEV -The WordPress Experts   Hosted by Microsoft MVPs