Is there any use to using char instead of a string for single-character values?

For .NET fields and properties that by definition contain only one character, is there any use to defining them as char instead of a string? Or is it a misuse of char data type?

I think of a field that can contain M or F for sex, or the average initial value, or an indicator stored in the database as Y or N. I usually define them as a string, but I wonder if I should define them as char.

+5
source share
4 answers

Yes, the charcorrect data type for this. General rule: always choose the narrowest (most restrictive) data type that is possible in context. This means that any invalid (or out of range) data will not be accepted if it gets accidentally, so your program / database will become less error prone.

To look at it from a different angle: if you want to use an integer value in your code, do you create an integer array of size one? Of course not, because although he will do the job, this is completely optional. i.e. Compare:

int[] value = new int[1] { 123 };
value[0] = 456;

in

int value = 123;
value = 456;

-, , , . , ( , string), , .

, , , (.. char) .

, , string . , , , , . , , , , char.

+12

A Char 1 String , . CLR , - ( , ).

, - . . , :

enum Gender { Male, Female }

class Foo
{
    Gender gender;
    Char middleInitial;
    Boolean indicator;
}

, . .

+4

- , , , /, (, ), , , , .

+2
source

The string class will have some overhead. If you have a char, will you need to represent an empty value with 0x00 or <space>or another unknown indicator? Will it be collected or received from the database, and what agreement are you going to use there?

I usually prefer enums / bools / native semantics at the application level for this, translating from and to any agreement with the database. After all, Person.Gender == Femalethey are if (!Person.IsDeceased) {}more readable and understandable.

+1
source

All Articles