Document directory
- 3. Constantly refactor your code
1. Do not use ", use string. Empty
string name = string.Empty;
2.Good at merging if
public bool Equals(CommentData obj) {
if (!CommentId.Equals(obj.CommentId)) return false;
if (!Comment.Equals(obj.Comment)) return false;
if (!CommentorId.Equals(obj.CommentorId)) return false;
return true;
}
--------- >>>
Public bool Equals (CommentData obj ){
Return CommentId = obj. CommentId &&
Comment. Equals (obj. Comment )&&
CommentorId = obj. CommentorId;
}
3. Constantly refactor your code
4. Simplify code with Linq
foreach (CommentData data in Comments) { if (data.CommentId.HasValue) throw new ArgumentNullException("Create is only for saving new data. Call save for existing data.", "data"); }
--------------->>>
if (Comments.Any(data => data.CommentId.HasValue)) { throw new ArgumentNullException("Create is only for saving new data. Call save for existing data.", "data"); }5. Use? : And ??
string name = value; if (value == null){name = string.Empty;}------------>>>
string name = (value != null) ? value : string.Empty;
Or: string name = value ?? String. Empty;
6. Useif (employee is SalariedEmployee){ var salEmp = (SalariedEmployee)employee; pay = salEmp.WeeklySalary; // ...}----------------------------------- >>>
var salEmployee = employee as SalariedEmployee;if (salEmployee != null){ pay = salEmployee.WeeklySalary; // ...}7. Use using to remove dispose ()
public IEnumerable<Order> GetOrders(){ SqlConnection con = null; SqlCommand cmd = null; SqlDataReader rs = null; var orders = new List<Order>(); try { con = new SqlConnection("some connection string"); cmd = new SqlCommand("select * from orders", con); rs = cmd.ExecuteReader(); while (rs.Read()) { // ... } } finally { rs.Dispose(); cmd.Dispose(); con.Dispose(); } return orders;}------------------------------- >>>
public IEnumerable<Order> GetOrders(){ var orders = new List<Order>(); using (var con = new SqlConnection("some connection string")) { using (var cmd = new SqlCommand("select * from orders", con)) { using (var rs = cmd.ExecuteReader()) { while (rs.Read()) { // ... } } } } return orders;} Simplified again:
public IEnumerable<Order> GetOrders(){ var orders = new List<Order>(); using (var con = new SqlConnection("some connection string")) using (var cmd = new SqlCommand("select * from orders", con)) using (var rs = cmd.ExecuteReader()) { while (rs.Read()) { // ... } } return orders;}