Saturday, December 25, 2010

Let.It.Be

Just another stupid question, bad for checking knowledge, but good enough to find out one's "tactical" architecture design capabilities.

It's not a secret that C# translates LINQ queries into chain of extension method calls. For instance, the following code snippet:

var entities = from e in list
               where e.Id > 10
               select e.Name;

will be transcribed as

var entities = list.Where(e=>e.Id > 10).Select(e=>e.Name);

But how is 'let' keyword transcribed? There is no .Let() method in LINQ. Could you suggest your solution?

Friday, November 19, 2010

Commutativity and LINQ

Yet another stupid questions. Imagine, you have defined a class:

class Entity{
 public int Id { get; set; }
 public int Priority { get; set; }
}

And also you have some sequence of Entity objects (i.e. IEnumerable entities). You need to group entities by its Id and select only entities with priority greater than 5.

As far as "and" is commutative and according to the task the following two blocks of code should return the same result


var group1 = entities.Where(e=>e.Priority > 5).GroupBy(e=>e.Id);
and
var group2 = entities.GroupBy(e=>e.Id).Select(g=>g.Where(e=>e.Priority > 5));

But this is wrong. There are two different sets of input data that will produce to different results (by two different reasons). Could you find them out?

Monday, November 1, 2010

Why IEnumerator<T> is IDisposable

Recently I've posted that IEnumerator<T> is IDisposable, but had not explained, why it is.

The explanation is rather simple - because of "yield return". Let's track this down.

Thursday, October 28, 2010

Static cache

Let's try to resolve a pretty regular case - some kind of key-value static cache. If there is no stored value for the specified key, the cache will call some external routine to get value and add it to the internal dictionary.

Here is a naive approach of the cache. It is straightforward enough.

public class Cache<TKey, TValue>
{
  Func<TKey, TValue> _resolver;
  Dictionary<TKey, TValue> _cache = new Dictionary<TKey, TValue>();

  public Cache(Func<TKey, TValue> resolver)
  {
    _resolver = resolver;
  }

  public TValue this[TKey key]
  {
    get
    {
       TValue value;
       if (!_cache.TryGetValue(key, out value))
       {
         value = _resolver(key);
         _cache.Add(key, value);
       }
       return value;
    }
  }
}

And also somewhere in a client code:
class ClientCode
{
  static Cache<TKey, TValue> _cache = new Cache<TKey, TValue>(Resolver);
}
Where Resolver is an user-defined function to get a value from the outer source.

Tuesday, October 12, 2010

Order zen

Pretty interesting question (and a good one for interview as well).

An Enumerable class contains two sets of methods: OrderBy() and ThenBy(). The first set sorts the elements of a sequence, second one performs a subsequent ordering of the elements in a sequence. If you have a sequence of names as {FirstName, LastName} and what to sort it by first name and then by last name you probably will not write as following:
var sorted = names.OrderBy(x=>x.FirstName).OrderBy(x=>x.LastName)

This is obviously wrong because you will firstly sort the sequence by FirstName and then resort it by LastName. To do the requested thing, you'll write:
var sorted = names.OrderBy(x=>x.FirstName).ThenBy(x=>x.LastName)

And here is the question - how ThenBy() is implemented (or how would you implement ThenBy() method)?

Monday, October 11, 2010

The vassal of my vassal is not my vassal

Just a thumb rule - avoid creating a PropertyExpression using

public static MemberExpression Expression.Property(Expression expression, MethodInfo property)

Instead prefer

public static MemberExpression Expression.Property(Expression expression, PropertyInfo property)

Tuesday, October 5, 2010

Interview

I would like to ask the following questions/tasks on a technical interview.
  1. Implement a singleton.
    Yes, kinda boring question. But I'll expect simple implementation, like follows:

    public class Singleton{
      private Singleton(){}
      public static Singleton Instance = new Singleton();
    }

    and nothing more. There is no words about laziness. Anything more complicated signals about over-engineering.
  2. Implement (I)Disposable pattern. And after it - When does a type need a finalizer?
    Second part is simple, first part is not good without explanation. In this case I'll wait for

    protected virtual void Dispose(bool isDisposing)

     
  3. ...to be continued

Tuesday, September 21, 2010

Equals vs Equals

Could you create an example, when System.Object.Equals(a,b) will return true and a.Equals(b)will return false


And moreover, why does your example works and what paradigm have you violated to achieve the result?

Wednesday, September 15, 2010

default(Type)

Just another stupid question. In C# there is a default keyword, that allows to get a default value for a given type - null for reference types and some defined value for value types. Actually, if T is value type, "default(T)" is equals to "new T()". This keyword works in compile time and a compiler will substitute it with corresponding value.
But how could I get a default value in runtime, when I have System.Type object?

PropertyInfo.SetValue()

Consider the following example.

We have a class named Foo:
class Foo
{
public int Bar{get;set;}
}


What is the result of the following code execution?

var property = typeof(Foo).GetProperty("Bar");
Foo foo = new Foo {Bar = 5};
property.SetValue(foo, null, null);
Console.WriteLine(foo.Bar);

Monday, September 13, 2010

Difference between reference type and value type

Consider the following example. You need to create a dynamic method with the following signature:
void SetValue(object instance, object value)
{
}

The method should set the given value to the specified property in the instance object. Property should be specified by its PropertyInfo.
Alas, Expressions in .NET 3.5 don't allow to create complex expressions and functors. So the solution is to use DynamicMethod from System.Reflection.Emit:

Thursday, September 2, 2010

How to start dump analysis with WinDbg

Just a side note.
  1. Open a dump of interest
  2. Load SOS extensions by executing
    .loadby sos mscorwks
  3. If you receive the error like "Failed to load data access DLL", check your symbol path with ".sympath" command. To set the correct sympath, use
    .sympath srv*c:\mycache*http://msdl.microsoft.com/download/symbols
    and then reload dlls with
    .cordll -ve -u -l

Sunday, August 22, 2010

#1 Params

A simple question. What would be printed out after execution?

void Main()
{
 Foo();
 Foo(null)
 Foo(null as object)
}

void Foo(params object[] args)
{
 if (args == null)
  Console.WriteLine("Null");
 else
  Console.WriteLine(args.Length);
}


* This source code was highlighted with Source Code Highlighter.

Thursday, August 19, 2010

#3 Enum.ToString()

It's kinda surprise, but Enum.ToString() uses reflection to get a string representation of an enum:
public override string ToString()
{
  Type type = base.GetType();
  object obj2 = ((RtFieldInfo) GetValueField(type)).InternalGetValue(this, false);
  return InternalFormat(type, obj2);
}


* This source code was highlighted with Source Code Highlighter.
This approach leads to visible performance issues when an application widely uses enum.ToString() (Obviously, any enum).

This issue could be fixed with the following trick code:
static class EnumHelper
{
  static class Cache<T>
  {
    internal static readonly Dictionary<T, string> Values = new Dictionary<T, string>();
  }
    
  public static string FastToString<T>(this T @enum) where T:struct
  { 
    if (!typeof(T).IsEnum)
      throw new ArgumentException(string.Format("Type {0} is not an enumeration.", typeof(T)));
    lock (Cache<T>.Values)
    {
      string result;
      if (!Cache<T>.Values.TryGetValue(@enum, out result))
      {
        result = @enum.ToString();
        Cache<T>.Values.Add(@enum, result);
      }
      return result;
    }
  }
}

* This source code was highlighted with Source Code Highlighter.
And, of course, all enum.ToString() should be replaced with enum.FastToString().

Wednesday, August 18, 2010

Total Commander Find Files and Subversion

When you're trying to search some file in a folder under subversion control, you receive a slight performance degradation, especially when you trying to find some text inside files. Total Commander tries to search inside ".svn" files and folders.
There is a good trick for such cases - Total Commander supports some tiny syntax to be used in "Search for:" field. So to exclude some files or folders from the search, you can put them into "Search field:" after a '|' sign. Note that wildcards can be used in include/exclude directory names, and the names must have a trailing backslash '\'.

For example:
  • w*.*|*.bak *.old finds files, which start with w and do not end with .bak or .old.
  • SomeFile.cs | .svn\ finds 'SomeFile.cs' not looking into subversion folders.

#2.5 Usings and Enumerators

One more thing regrading using. Do not forget, that IEnumerator<T> is IDisposable (though, IEnumerator is not).
public interface IEnumerator<T> : IDisposable, IEnumerator
{
  // Properties
  T Current { get; }
}


* This source code was highlighted with Source Code Highlighter.


So do not forget to enclose GetEnumerator() calls to using statement.

#2 Usings

Just not to forget, that there could be multiple objects in a using statement:
using (Font font3 = new Font("Arial", 10.0f),
      font4 = new Font("Arial", 10.0f))
{
  // Use font3 and font4.
}

* This source code was highlighted with Source Code Highlighter.

Though, all objects should be of the same type, the following is not allowed:
using (IEnumerator<T1> firstEnumerator = first.GetEnumerator(),
    IEnumerator<T2> secondEnumerator = second.GetEnumerator())
{
  // ...
}


* This source code was highlighted with Source Code Highlighter.