Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fixed string size in C#

Tags:

string

c#

The short question: Is it possible to create a fixed size string in C#? I know that in VB it's possible declaring something like this: str AS string * 20

The long story: I need to read a binary file that contains a 20 byte field into a string. I read the content of the file into an object (class). I want to limit the strings in the object in the class definition.

Thank you very much for your concern.

roi

like image 953
roishabtai Avatar asked Apr 10 '11 13:04

roishabtai


People also ask

What is the size of string variable in C?

The string length in C is equal to the count of all the characters in it (except the null character "\0"). For Example, the string "gfddf" has a length of 5 and the string "4343" has a length of 4.

Do arrays have fixed size in C?

Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

Is the fixed-length string data type?

A fixed-length column requires the defined number of bytes regardless of the actual size of the data. The CHAR data type is of fixed-length. For example, a CHAR(25) column requires 25 bytes of storage for all values, so the string “This is a text string” uses 25 bytes of storage.

What is the size of string?

A string is composed of: An 8-byte object header (4-byte SyncBlock and a 4-byte type descriptor)


3 Answers

You could declare and fill a fixed size char array, and then pass that to the String objects constructor to make the string from that.

var newString = new string(theCharArray);

like image 77
Michael Low Avatar answered Oct 14 '22 07:10

Michael Low


You should create a property of type string that checks value.Length in the setter and truncates it or throws an exception.

like image 33
SLaks Avatar answered Oct 14 '22 05:10

SLaks


You should use 'StringBuilder' for your issue.

like image 1
iehrlich Avatar answered Oct 14 '22 06:10

iehrlich