ไม่ได้เขียน Blog แนวโปรแกรมมานานขอรวบรวม C# 3.0 (ตอนนี้กำลังจะออก 4.0) ไว้ก่อนล่ะกัน
1. The ? conditional evaluation operator
เป็นการย่อคำสั่งที่เป็นเงื่อนไข if .. then .. else จากเดิม
int x = 10; int y = 20; int max; if (x > y) max = x; else max = y;
เขียนใหม่เป็น
int x = 10; int y = 20; int max = (x > y) ? x : y;
2. Null-Coalesce operator (??)
เป็นการตรวจสอบค่า null ของตัวแปล เช่น
object cache = null; object d = new object(); object e; if (c != null) e = c; else e = d;
หรือ
object cache = null; object d = new object(); object e = (c != null) ? c : d;
เราสามารถใช้เครื่องหมาย "??" เพื่อทำให้สั้นลงเขียนใหม่เป็น
object cache = null; object d = new object(); object e = c ?? d;
3. Object Initializers
เวลาที่เราประกาศ instance ของ class เรามักจะเขียนแบบนี้
Customer c = new Customer(); c.Name = "James"; c.Address = "204 Lime Street";
สามารถเขียนให้สั้นลงเป็น
Customer c = new Customer { Name="James", Address = "204 Lime Street" };
4. The using statement
เวลาที่เรียกใช้และกำหนดค่า System Resouce เช่น Font , File , Network ต่างๆ เราจะเขียนแบบนี้
// 1. Allocation of the object Font font1 = new Font("Arial", 10.0f); try { // 2. The bit where we use the resource } finally { // 3. Disposal of the object if (font1 != null) ((IDisposable)font1).Dispose(); }
เราสามารถเขียนได้อีกแบบคือ
// Allocate the resource using (Font font1 = new Font("Arial", 10.0f)) { // The bit where we use the resource } // Disposal is automatic
5. Aliases for long winded namespaces and types
เรียกใช้ NameSpace แบบเร่งรัด
using Word = Microsoft.Office.Interop.Word; ... Word.Application = new Word.Application() { Visible = True; }
6. Nullable objects
เราสามารถกำหนด Data type ให้สามารถมีค่า null ได้
Nullable<int> x = null; int? x = null;
7. Automatic Properties
ใน C# 3.0 เราสามารถกำหนด properties ได้อย่างรวดเร็ว ปกติเราจะเขียนแบบนี้
public class Person { private string _firstName; public string FirstName { get { return _firstName; } set { _firstName = value; } } }
เขียนใหม่เป็น
public class Person { public string Firstname { get; set; } }
8. Type inference
การประกาศตัวแปลจากเดิม
string MyString = “Hello World”;
เขียนใหม่ได้เป็น
var MyString = “Hello World”;
9. Lambda Expressions
ใน C# 2.0 จะมี anonymous methods และมี delegate มาเกี่ยวข้อง เช่น
Func mySeniorStaffFilter = delegate(int a) { return a > 35; };
เราสามารถใช้ syntax ของภาษา Lamda สามารถเขียนให้อ่านง่ายขึ้น
Func mySeniorStaffFilter = a => a > 35;
และสามารถเขียนได้ทุกที่ ที่เราต้องการ filtter ข้อมูล
var SeniorStaff = Employees.Where(s => s.Age > 35);
10. string.IsNullOrEmpty
ใช้ string.IsNullOrEmptyเพื่อตรวจสอบ ข้อมูลว่าง และ ข้อมูลมีค่าเป็น null เฉพาะข้อมูลที่เป็น string
if (String.IsNullOrEmpty(s) == true) return "is null or empty"; else return String.Format("(\"{0}\") is not null or empty", s);
มาดู C# 4.0 ว่ามีอะไรใหม่บ้างใน Blog ถัดไปล่ะกัน :P
