Write a little less code with IEnumerable and yield

by andrei 26. September 2008 06:48

I was used to creating many IList<T> classes, but recently I started using IEnumerable<T> more. The more I use it, the more I realize it is enough for most situations.

 

Here is the relation between IList<T> and IEnumerable<T>:

ScreenHunter_01 Sep. 26 19.42

 

A nice thing with IEnumerable is that it works with yield, so instead of writing this:

private IList<int> GetIds()
{
  IList<int> list = new List<int>();

  foreach (RepeaterItem item in rptData.Items)
  {
    HiddenField hdnId = item.FindControl("hdnId") as HiddenField;
    if (hdnId != null)
      list.Add(Convert.ToInt32(hdnId.Value));
  }

  return list;
}

you can write this:

private IEnumerable<int> GetIds()
{
  foreach (RepeaterItem item in rptData.Items)
  {
    HiddenField hdnId = item.FindControl("hdnId") as HiddenField;
    if (hdnId != null)
      yield return Convert.ToInt32(hdnId.Value);
  }
}

which is a little less code. And you can still do a foreach over the result.

 

 

Enjoy programming!

 

The implicit keyword

by andrei 14. September 2008 21:32

In case you did not know, here is a C# trick which can make your code even more readable: the implicit keyword. This keyword can save you from doing explicit casts with many occasions.

 

Here is how it works:

class ImplicitClass
{
  private readonly string _name;
  private readonly string _value;

  public ImplicitClass(string name, string value)
  {
    _name = name;
    _value = value;
  }

  public static implicit operator string(ImplicitClass source)
  {
    return source._name;
  }

  public static implicit operator int(ImplicitClass source)
  {
    return Convert.ToInt32(source._value);
  }
}

public class ImplicitTest
{
  private void ImplicitTestMethod()
  {
    ImplicitClass implicitClass = new ImplicitClass("className", "2");
    string name = implicitClass; // name becomes "className"
    int value = implicitClass; // value becomes 2
  }
}

Nice.

 

UPDATE: One of my fellow developers at Akcedo pointed out that the implicit operator does not make the code more readable, instead it makes it less readable. Only then I stopped and processed the implications, and... well, he is right.

 

The conclusion about the operator is: use it with care, always considering that it must be easy to understand. If the person who reads the assignment code (string name = implicitClass;) also needs to read the internal code of the operator (return source._name;) to understand what it does, you should not use an implicit operator.

 

 

Enjoy programming!

 

Powered by BlogEngine.NET 1.4.5.0