Để tạo string object trong C#, dùng một trong các cách:
- Gán string literal cho biến String
- Dùng String class constructor
- Dùng toán tử nối chuỗi (+)
- Lấy property hoặc gọi method trả về string
- Gọi formatting method chuyển giá trị/đối tượng thành string
Ví dụ
using System;
namespace Demo {
class Program {
static void Main(string[] args) {
// từ string literal và nối chuỗi
string fname = "Brad ", lname = "Pitt";
string fullname = fname + lname;
Console.WriteLine("Full Name: {0}", fullname);
// dùng string constructor
char[] letters = { 'W', 'e', 'b' };
string greetings = new string(letters);
Console.WriteLine("Greetings: {0}", greetings);
// method trả về string
string[] sarray = { "Web", "World" };
string message = String.Join(" ", sarray);
Console.WriteLine("Message: {0}", message);
// formatting method
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);
}
}
}
Kết quả
Full Name: Brad Pitt Greetings: Web Message: Web World Message: Message sent at 5:58 PM on Wednesday, October 10, 2012