Friday, June 20, 2008

C# Puzzle No.6 (intermediate)

If you have correctly solved the 5th C# puzzle, you should have no problems in predicting the output of following code snippet (without actually running it):

List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
 
list.Where( i => { Console.WriteLine( i ); return i < 5; } );

Thursday, June 19, 2008

C# Puzzle No.5 (intermediate)

Can you predict the output of the code above without actually running it?

List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
 
list.FindAll( i => { Console.WriteLine( i ); return i < 5; } );

C# Puzzle No.4 (intermediate)

It is common to use the lambda expression syntax. Whenever a method is required expecting a parameter and returning something, you can provide

parameter => expression

instead of boring



ReturnType Foo( ParameterType parameter )
{
    expression;
}

and then compiler will interfere types for you for both parameter and expression.


The question is, how do you provide lambda expressions for delegates which expects no parameters?



delegate int FooDelegate();
static void Foo( FooDelegate Delegate )
{
    Console.WriteLine( Delegate() );
}
 
static void TheProblem()
{
   Foo( * );
}

Your goal is to fill the * above with the lambda expression equivalent to following delegate:



int ConvertThisToLambdaExpression()
{
  return 5;
}

C# Lambda Expressions Can Contain Method Bodies

I know a lot of people who love and use the lambda expression syntax provided in C# 3.0 as a shortcut for explicit delegate definitions.

Suprisingly however, quite few of them actually know that lambda expression can not only have a suprisingly variable => expression form like:

x => x < 5

but can also contain method bodies as expressions like



x => { Console.WriteLine( x ); return x < 5; }

Monday, June 16, 2008

C# 3.0 Mixins with Interfaces, Extension Methods Wrapper Classes and Implicit Conversion Operators

Mixin is a programming language technique in which you extend classes with methods and properties by so called mixins. In C++ mixins are easily achieved using multiple inheritance, while in C# or Java you have to find out how to work around the single inheritance.

There is a long discussion on the matter and people are proposing ways to build mixins in C#. What they usually focus on is extending classes with additional methods (here or here) while, in fact, mixins is not only about methods but also about other class members. In his blog, Colin Mackay has pointed three possible ways to actually build mixin extensions which can hold data.

What I'd like to point out is that there is yet another possibility based on inheritance but this time you inherit from extended classes rather than making them inherit from a base class. In case of structures which are sealed, you just create wrapper classes.

Let's start with the mixin declaration:

interface IMixin
{
    int TheProperty { get; set; }
}
 
static class IMixinExtension
{
    public static void Extension1( this IMixin Mixin )
    {
        Console.WriteLine( "Value of mixin property: " + Mixin.TheProperty.ToString() );
    }
}

The interface describes mixin structure while the extension method adds a logic for it. Now we are ready to augment classes.



class StringMixin : IMixin
 {
     string _string;
     public StringMixin( string String )
     {
         this._string = String;
     }
 
     #region IMixin
     public int TheProperty { get; set; }
     #endregion
 
     #region Conversion
     public static implicit operator string( StringMixin Mixin )
     {
         return Mixin._string;
     }
 
     public static implicit operator StringMixin( string String )
     {
         return new StringMixin( String );
     }
     #endregion
 
     #region Delegated methods
     public override string ToString()
     {
         return _string.ToString();
     }
 
     public string ToLower()
     {
         return _string.ToLower();
     }
 
     // etc...
     #endregion
 }

As you can see it's not quite ellegant because there's no default delegation so I cannot delegate methods from System.string to the _string member of the class, however from the client's point of view, StringMixin is just a string with additional properties:



class StringClient
{
    public static void ExpectsString( string String )
    {
        Console.WriteLine( String );
    }
}
 
class Program
{
    static void Main( string[] args )
    {
        StringMixin mixin = "The string";
 
        StringClient.ExpectsString( mixin );
    }
}

On the other hand, extended class behaves just as mixin is supposed to behave: it has been augmented with additional members but base members are still there:



class Program
{
    static void Main( string[] args )
    {
        StringMixin mixin = "The string";
 
        // it's still a string
        Console.WriteLine( mixin.ToLower() );
        // but augmented with properties
        Console.WriteLine( mixin.TheProperty.ToString() );
        // and methods
        mixin.Extension1();
    }
}

Note that since the original class is wrapped, the wrapper can contain any additional data  so the "dataless mixins" issue is gone.


The drawback is obvious : you need extra wrapper class for each class you'd like to augment with a mixin. Note that in case of reference types there's no need to wrap - instead of wrapping the class you can just inherit from it.

Thursday, June 12, 2008

C# Puzzle No.3 (level: beginner)

Can two static variables which refer to each other cause an infinite recursion?

public class A
{
  public static int a = B.b + 1;
}

public class B
{
  public static int b = A.a + 1;
}
 
public class MainClass
{
  public static void Main()
  {
    Console.WriteLine( "A.a={0}, B.b={1}", A.a, B.b );
  }
}

Can you explain what would be the output (if any) of the above code without actually running it?

C# Puzzle No.2 (level: intermediate)

Following code snippet is commonly used in C/C++ to exchange values of two integer values with no help of any additional variable.

int x, y;
 
x ^= y ^= x ^= y;

This surprisingly does not work in C#. Can you explain why?