Updated C# implementation.