Braintique.com header
Left Navigation Bar

String Constructors

The String class itself has eight constructors. If you look in the Object Browser, you’ll find that five of these use pointers and are not safe under the rules of the Common Language Specification (CLS) that .NET languages must follow.

String Contructors

The unsafe constructors are not discussed here. The remaining three safe String overloaded constructor methods are shown in the table below.

Table: Overloaded Safe String Class Constructors

Method

Meaning

String (char, int)

Creates a string consisting of a char repeating int times.

String (char[])

Creates a string from a char array.

String (char[], int, int)

Create a string from a char array with a start position and length.

                         

Let’s have a look at an example that uses these constructors. It’s easy to use the first form and create a string consisting of the lowercase letter a 23 times:

string str1 = new String ('a', 23);

To use the second form, we must first create a char array:

char [] achra = new char[6] {'H', 'e', 'l', 'l' ,'o', '!'};
string str2 = new String (achra);

Third time pays for all! First, let’s initialize a string:

string str3 = "Beasts of England";

Next, we can use the string’s ToCharArray method to turn it into a char array:

char [] achra2 = str3.ToCharArray();

Finally, it’s a hop, skip, and a jump to assign the first six elements of the char array to a string:

str3 = new String (achra2,0,6);

The listing shows the code that uses the three constructors and displays the results in a ListBox.

Listing: The Safe String Constructors

private void btnStr_Click(object sender, System.EventArgs e) {
lstStr.Items.Clear();
string str1 = new String ('a', 23);
char [] achra = new char[6] {'H', 'e', 'l', 'l' ,'o', '!'};
string str2 = new String (achra);
string str3 = "Beasts of England";
char [] achra2 = str3.ToCharArray();
str3 = new String (achra2,0,6);
lstStr.Items.Add (str1);
lstStr.Items.Add (str2);
lstStr.Items.Add (str3);
}


List Box

Previous Table of Contents Next


Google
 
Web www.braintique.com
www.digitalfieldguide.com www.googleplexblog.com


Home | Barticles | Blogs | Books | Services | FAQ | Contact

© Braintique.com. All rights reserved.

Search Engine Optimization







RSS 2.0 Syndication feed

Syndication Viewer

Our Web host:
IX WebHosting



Food for Your Brain! Get a Barticle! Questions Answered Books for You What We Can Do For You Contact Us Brain Food Questions Answered Books for You What We Can Do For You Frequently Asked Questions About Us Google Research Photoshop Wi-Fi and Wireless Networking The Natural Way to Write