Archive for CSharp tag
Extension methods illustrated
Extension methods are a great new feature in the .NET Framework 3.5 that let you write new methods that appear to be part of existing classes without the need to subclass or modify them.
We can explain this in simple terms with an example. Here is a useful routine that takes a string and returns what it finds between two other strings that works just fine with .NET 2.0 and .NET 1.1.
public static string Between(string value, string start, string end) {
int startIndex = value.IndexOf(start, StringComparison.CurrentCultureIgnoreCase);
if (startIndex == -1)
return "";
startIndex += start.Length;
int endIndex = value.IndexOf(end, startIndex, StringComparison.CurrentCultureIgnoreCase);
if (endIndex == -1)
return "";
return value.Substring(startIndex, endIndex-startIndex);
}
If this method belonged to a static StringUtilities class then you could use it like this:
string newString = StringUtilities.Between(inputString, startingString, endingString);
The problem is knowing that the StringUtilities class within the project you are working on and until you know that IntelliSense can’t even kick in. What would be nice is to add this to the String class but of course we can’t because String is sealed and besides methods everywhere create String classes and not instances of your subclass.
What would be really cool is if Visual Studio and .NET could just realise that this method is static and takes a string parameter as it’s first parameter and let it just appear as another method on the String class and just call StringUtilities behind the scenes.
That is exactly what the extension methods in .NET 3.5 achieve.
All we need to do is put this in front of the first parameter which will let VS and the compiler know that this method should appear as if it is a method against the type of that first parameter. The method must be static and visible to the code and curiously the class itself must also be static. Our signature now appears as:
public static string Between(string this value, string start, string end)
To call the method we simply press . after our string and IntelliSense displays all the usual methods and properties of the String class and any extension methods it can find in your project too which now includes our Between method giving us:
string newString = inputString.Between(startingString, endingString);
Nice but bear in mind the extension method can only access the public parts of the class it will appear with – there is no privileged access to protected properties or methods that would be available with subclassing!
[)amien
Multiple-inheritance, composition and single responsibility principle in .NET
.NET is often chided by C++ developers for failing to support multiple-inheritance. The reply is often Favor object composition over class inheritance – a mantra chanted from everywhere including the opening chapters of the Gang of Four’s Design Patterns book.
If the accepted mantra is that your object should expose interfaces and delegate the implementation of those interfaces elsewhere then it could really do with some better support than .NET currently offers especially where the interface comprises more than a member or two.
Consider the following fragment of a class for customer price-lists (properties and methods omitted). We decide to support IList<ProductPrice> so that consumers of our class can add, remove and iterate over the prices in a familiar manner (principle of least surprise).
public class CustomerPriceList : IList<ProductPrice> {
private List<ProductPrice> productPrices = new List<ProductPrice>();
public Customer Customer;
}
Implement interface
Visual Studio offers some assistance where you can choose Implement interface IList<ProductPrice> which gives you all the method definitions with the very unhelpful body of throwing an exception of “This method or operation is not implemented”. It requires some work to fill in all these definitions to something that works:
public class CustomerPriceList : IList<ProductPrice> {
private List<ProductPrice> productPrices = new List<ProductPrice>();
public Customer Customer;
public int IndexOf(ProductPrice item) {
return productPrices.IndexOf(item);
}
public void Insert(int index, ProductPrice item) {
productPrices.Insert(index, item);
}
public void RemoveAt(int index) {
productPrices.RemoveAt(index);
}
public ProductPrice this[int index] {
get { return productPrices[index]; }
set { productPrices[index] = value; }
}
public void Add(ProductPrice item) {
productPrices.Add(item);
}
public void Clear() {
productPrices.Clear();
}
public bool Contains(ProductPrice item) {
return productPrices.Contains(item);
}
public void CopyTo(ProductPrice[] array, int arrayIndex) {
productPrices.CopyTo(array, arrayIndex);
}
public int Count { get { return productPrices.Count; } }
public bool IsReadOnly { get { return ((IList)productPrices).IsReadOnly; } }
public bool Remove(ProductPrice item) {
return productPrices.Remove(item);
}
public IEnumerator<ProductPrice> GetEnumerator() {
return productPrices.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() {
return ((IEnumerable) productPrices).GetEnumerator();
}
}
This is a lot of effort for a cluttered solution.
Use inheritance to subclass List<T>
public class CustomerPriceList : List<ProductPrice> {
public Customer Customer;
}
Small amount of code but not an option if you have a class hierarchy in place or need to implement multiple interfaces.
Expose IList<ProductPrice> property directly
public class CustomerPriceList : IListable<ProductPrice> {
private List<ProductPrice> productPrices = new List<ProductPrice>();
public Customer Customer;
public IList<ProductPrice> ProductPrices { get { return productPrices; } }
}
This works but means CustomerPriceList can not control any of the IList implementation such as validation.
Methods may also start accepting IList<ProductPrice> instead of CustomerPriceList because developers imagine the parts to be more decoupled than they actually are and are encouraged to code to interfaces not concrete classes.
Refactoring away from this at a later date would require a IList<ProductPrice> wrapper than delegated calls back to the containing class to prevent an interface-breaking change.
Introduce interface to declare IList<ProductPrice> available
Add an interface that signifies a IList<ProductPrice> can be obtained by calling the named method, e.g.
public interface IListable<T> {
IList<T> GetList();
}
This is a similar pattern to that of IEnumerable<T> and IEnumerator<T> whereby one interface signifies the availability of the other. In this example our class would look like:
public class CustomerPriceList : IListable<ProductPrice> {
private List<ProductPrice> productPrices = new List<ProductPrice>();
public Customer Customer;
public IList<ProductPrice> GetList() {
return productPrices;
}
}
Which is less code, a closer adherence to single responsibility principle (SRP) and the ability to change without breaking the interface although it still does nothing to prevent passing IList or IListable interfaces where CustomerPriceList would be more suitable. An IPriceList class could be introduced although it starts to feel like abstract infinity.
Improved support from .NET
I’d really like to see .NET improve on the support for interfaces and composition, like perhaps the following:
public class CustomerPriceList : IList<ProductPrice> goto productPrice {
private IList<ProductPrice> productPrice = new IList<ProductPrice>();
public Customer Customer;
}
This would signify to the compiler that all IList<T> interfaces should be wired up to the productPrice variable unless explicitly defined and gives goto a whole new lease of life ;-)
[)amien
.NET quick samples: Uptimes, ages, rounding to n places
Just a few quick .NET samples for performing some common tasks that the .NET Framework doesn’t do for you:
System uptime
using System.Diagnostics;
public TimeSpan GetUptime() {
PerformanceCounter systemUpTime = new PerformanceCounter("System", "System Up Time");
systemUpTime.NextValue(); // Required to work!
return TimeSpan.FromSeconds(systemUpTime.NextValue())));
}
Calculating age
public int GetAge(DateTime birthday) {
int years = DateTime.Now.Year - birthday.Year;
return (birthday.DayOfYear >= DateTime.Now.DayOfYear) ? years : years - 1;
}
Rounding to n decimal places
public decimal ArithmeticRound(decimal d, int decimals) {
decimal power = (decimal)Math.Pow(10, decimals);
return (decimal.Floor((Math.Abs(d) * power) + 0.4m) / power) * Math.Sign(d);
}
[)amien
Subtleties of .NET: int i; and int i=0 are not the same
Every value type in .NET defaults to a sensible value so you might be thinking that
int i
and
int i = 0
are logically the same.
This is often true however consider the case of a variable declared in-line inside a loop and things are a little different (using Decimal in this example)
foreach(Customer customer in customers) {
decimal customerSalesYTD = 0;
foreach(Invoice invoice in customer.Invoices.ForYear(DateTime.Now.Year)
customerSalesYTD += invoice.Value;
SalesTotal.Set(customer, customerSalesYTD);
}
Here the 0 makes all the difference because although you have created the variable inside the loop by the time the runtime gets to this the optimizer has moved the object creation to outside the loop.
[)amien