To create a string object in C#, use any of the below given method.
- By assigning a string literal to a String variable
- By using a String class constructor
- By using the string concatenation operator (+)
- By retrieving a property or calling a method that returns a string
- By calling a formatting method to convert a value or an object to its string representation
The following is an example showing different ways to create a string object in C#.
Example
using System;
namespace Demo {
class Program {
static void Main(string[] args) {
//from string literal and string concatenation
string fname, lname;
fname = "Brad ";
lname = "Pitt";
char []letters= { 'W', 'e', 'b'};
string [] sarray={ "Web", "World"};
string fullname = fname + lname;
Console.WriteLine("Full Name: {0}", fullname);
//by using string constructor { 'W, 'e', 'b'};
string greetings = new string(letters);
Console.WriteLine("Greetings: {0}", greetings);
//methods returning string { "Web", "World" };
string message = String.Join(" ", sarray);
Console.WriteLine("Message: {0}", message);
//formatting method to convert a value
DateTime waiting = new DateTime(2012, 10, 10, 17, 58, 1);
string chat = String.Format("Message sent at {0:t} on {0:D}", waiting);
Console.WriteLine("Message: {0}", chat);
}
}
}Output
Full Name: Brad Pitt Greetings: Web Message: Web World Message: Message sent at 5:58 PM on Wednesday, October 10, 2012