TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Char Type

This C# article shows the char type. Chars are values, similar to ushort, that represent characters.

Char. The char type represents a character.

A value type, char is similar to an integer or ushort. It is two bytes in width. It must be cast when converting to an integer. With an indexer, we access chars in strings.

Example. To start, we access a char from a string. The char at index 4 is s. Strings are indexed starting at zero, so the fifth letter is at the fourth index. We store the char in a local variable with identifier c.

Also: We test the value of the char variable in an if-statement. Please notice how a char uses single-quotes around it.

Character Literal

Based on:

.NET 4.5

C# program that uses char literal

using System;

class Program
{
    static void Main()
    {
	char c = "perls"[4];
	if (c == 's')
	{
	    Console.WriteLine(true);
	}
    }
}

Output

True

Example 2. Next, this program performs some operations on a char variable after initializing it to the lowercase letter 'a'. We see an example of casting the char variable, comparing it to another variable, and obtaining its managed Type pointer.

Thus: We prove that when allocated on the managed heap, a char will occupy two bytes of storage, equivalent to a ushort integer.

C# program that demonstrates char type

using System;

class Program
{
    static void Main()
    {
	//
	// Declare a character and test in certain ways.
	//
	char value = 'a';
	Console.WriteLine(value);
	Console.WriteLine((int)value);
	Console.WriteLine(value == 'y');
	Console.WriteLine(value.GetType());
	Console.WriteLine(typeof(char));
	Console.WriteLine((int)char.MinValue);
	Console.WriteLine((int)char.MaxValue);

	//
	// Determine the memory usage for a single char.
	//
	long bytes1 = GC.GetTotalMemory(false);
	char[] array = new char[1000 * 1000];
	array[0] = 'a';
	long bytes2 = GC.GetTotalMemory(false);
	Console.WriteLine(bytes1);
	Console.WriteLine(bytes2);
	Console.WriteLine(((bytes2 - bytes1) / (1000 * 1000)).ToString() +
	    " bytes per char");
    }
}

Output

a
97                  (Integer value of char)
False
System.Char
System.Char
0                   (MinValue as an integer)
65535               (MaxValue as an integer)
29252               (Memory measurement 1)
2029284             (Memory measurement 2)
2 bytes per char

The program casts the char value to an integer value and displays it in a decimal form. This is useful for indexing arrays with characters. It also helps with compilation problems when adding characters together or comparing characters.

Tip: The C# language has specific rules relating to char conversions to integers.

Cast, Int

The typeof operator and the GetType virtual method on the char variable in the program both return the value System.Char. This type is a struct in the base class library that is aliased to the char keyword.

Struct

Note: When you use the char keyword, you can always use System.Char instead as they are the same.

TypeofGetType

Char memory usage. The final part of the program does a test to determine the byte size of the char data type when stored in an array. It allocates one million chars in an array on the managed heap, measuring memory before and after.

Then: It divides the memory difference by one million. The array is touched in memory with an assignment to ensure it is not optimized out.

And: The test indicates that a char requires two bytes in memory when part of an array.

GC.CollectDivide

Arrays. The char data type in the C# language is rarely used alone and you will usually be using it as part of an array or string type. You can easily convert character arrays to strings, and strings to char[] arrays.

Tip: You will often use character arrays in C# programs. These can be useful for optimizations, or for creating buffers.

Char ArrayToCharArrayConvert Char Array, String

Methods. There are many public static methods on the char type in the .NET Framework. Here we reveal several of these methods. Often these methods, with careful testing, can be replaced with an optimized expression.

char.IsControlchar.IsDigitchar.IsLetterOrDigitchar.IsLowerchar.IsPunctuationchar.IsSeparatorchar.IsWhiteSpacechar.ToLower

Strings. There are some subtleties to how chars work with the string type in the C# language. These articles attempt to provide answers to common questions about chars and the string type. We show some conversion operations.

String CharsSwitch CharCharEnumeratorConvert Char, String

Count characters. It is sometimes useful to gather statistics about the frequency of characters or the total number of non-whitespace characters. We test Microsoft Word to implement character counting in a C# method.

Count Characters in StringLetter Frequencies

Remove: We remove a character from a string. We can remove characters based on some other criterion, such as their frequency.

Duplicate CharsRemove Chars

ASCII. What characters are available in the ASCII character set? This article demonstrates code that programmatically prints each ASCII character and renders it as an HTML table. It helps us understand how ASCII values are represented.

ASCII Table

Performance. An important optimization to understand is the lookup table optimization. In this technique, you replace a computation with a lookup in a precomputed array. This improves performance in certain situations.

Char Lookup TableChar Lowercase

Also: There are other optimizations you can use on the char type. We optimize StartsWith and combine multiple chars into a string.

Char Test, StringChar Combine

Research. Char is a special type. I researched it in the C# specification. I found a char is similar to a ushort but with restrictions. At a high level, the types are used differently—this is enforced by the compiler.

Although char has the same representation as ushort, not all operations permitted on one are permitted on the other.

The C# Programming Language

Character is important. And so is the char type. For compatibility, a char in the C# language requires 2 bytes. This makes it less efficient. But speed is always less important than a program that works: a goal all programmers work toward.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf