Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Sunday, April 7, 2013

Lazy Evaluation And Infinite Data Structures In C#

Today I was reading the "Functional programming with Haskell" tutorial by Rob Harrop. In this article Rob also shows the ability of Haskell to handle the so called Infinite Data Structures using an infinite list of prime numbers as an example. The author defines infinite data structures as "data structures that abstract the details of some infinite stream of data". Due to Haskells support for lazy evaluation such infinite lists can be treated like normal lists. While reading the article I was wondering if I can do the same thing in C#. Though it's an eagerly evalutated language (means: the expression gets evaluated as soon as you assign it to a variable) using the yield keyword you can deal with infinite data structures:
public class Primes {
  public IEnumerable<int> All () {
    int number = 2;
    while (true) {
      while (!IsPrime (number)) ++number;
      yield return number++;
    }
  }

  public bool IsPrime (int number) {
    if(number < 3) return true;
    var seq = Enumerable.Range (2, number - 2);
    Func<int, int, bool> divides = (n,p) => n % p == 0;
    return seq.All(p => !divides (number, p));
  }
}
The Primes.All() method returns an "infinite" list of prime numbers. Thank to the yield keyword the numbers are not computed until you really use them, e.g. you can get the first ten prime numbers by:
var primes = new Primes ();
var firstTenPrimes = primes.All().Take(10);
With the power of the LINQ framework the Primes.All() method even becomes a "one liner":
public IEnumerable<int> All () {
  return Enumerable.Range (2, int.MaxValue - 1)
                   .Where (IsPrime);
}
I really like these functional features in C# :)

Monday, May 16, 2011

Unity: passing constructor parameters.

Unity is a dependency injection container from Microsoft. The version 2.0 is now available for download at codeplex: patterns & practices - Unity. You can use it to reduce dependencies in your .NET applications. Say you want to decouple your 'high level' code from the implementation details of the data access. With Unity you can define an interface like IDataContext and register the actual implementation in the Unity container:
var container = new UnityContainer();
container.RegisterType<IDataContext, SqlDataContext>();
In the 'high level' code you don't have to know the concrete type that implements the data access but just the contract: IDataContext. Unity will resolve the implementation you have registered at runtime:
var dataAccess = container.Resolve<IDataContext>();

Pretty easy so far but what if you want to pass a parameter to the constructor of your IDataContext implementation, e.g. a connection string? Just pass the value you want to be injected as a parameter when registering the type:
container.RegisterType<IDataContext, SqlDataContext>(
  new InjectionConstructor(connectionString));
Unity will pass the value you have defined here to a matching constructor of SqlDataContext when you will request an instance of it.

Friday, April 15, 2011

ReSharper's Object Initializer Quick Fix and IDisposable

This week I had to realize that not every Resharper suggestion is really useful. Some quick fixes carelessly applied can even introduce flaws into your code. The quick fix I have in mind is Resharpers suggestion to use an object initializer instead of creating an instance with subsequent assignments to its properties. Applying this quick fix to following code:
var person = new Person();
person.Name = "John";
person.Lastname = "Doe";
would change it to:
ver person = new Person {
     Name = "John", Lastname = "Doe" };
This quick fix is really handy and can imho improve the readability of the code. But it should not be applied when the type is an IDisposable! Why? An object initializer just creates a temporary instance of Person initializes the properties and then assignes this temporary variable to the variable person. Something like that:
var temp = new Person();
temp.Name = "John";
temp.Lastname = "Doe";
var person = temp;
The problem is that if an exception is thrown during the properties initialization you have no chance to dispose the new instance because you have no access to that temporary local variable. It's created by the compiler and is therefore not visible in you c# code. Even if you put the object initializer inside a try catch block or an using directive you will have a problem: http://ayende.com/Blog/archive/2009/01/15/avoid-object-initializers-amp-the-using-statement.aspx.

Things learned:

  1. Never use object initializers with types implementing IDisposable
  2. Resharper is a great tool but you should never apply quick fixes blindly. Think for yourself. Don't let the tools do the thinking for you ;)