work my way through snippets in http://csharpindepth.com/
Evoltion of Product type, showing greater encapsulation, stronger typing, and ease of initialization over time.
- read-only properties
- weakly typed collections
- private property setters
- strongly typed collections
- automatically implemented properties
- enhanced collections and object initialization
- named arguements for clearer constructor and method calls.
- weakly typed compartor
- no delegate sorting option
- strongly typed comparator
- delegate comparisons
- anonympous methods
- lambda expressions
- extension methods
- options of leaving list unsorted
- Strong coupling between condition and action.
- Both are hardcoded.
- seperate condition from action invoked.
- Anonymous methods make delegates simple.
- lambda expressions make the condition even easier to read.
If decimal were a reference type, you could just use null to reprsent the unknown price, but since it's a value type, you can't. How would you represent this in C# 1?
There are three common alternatives:
- Create a reference type wrapper around decimal.
- Maintain a separate Boolean flag indicating whether the price is known.
- Use a "magic value" (decimal.MinValue, for example) to represent the unknown price.
They all suck!
C# 2 alternatives
e.g. decimal? price; public decimal? Price { get { return price; } private set { price = value; } }
The constructor paramter changes to decimal?, and then you can pass in null as the
argument, or Price = null; within the class. The meaning of the null changes from
"a special reference that doesn't refer to any object" to "a special value of any
nullable type representing the absence of other data," where all reference types and
all Nullable<T>-based types count as nullable types.
- choice between extra work maintaining a flag
- changing to reference type semantics
- or the hack of a magic value
- nullable type make the "extra work" option simple
- syntactic sugar improves matters even further.
- optional parameters allow simple defaulting e.g. public Product(string name, decimal? price = null) { this.name = name; this.price = price; }