Two great .NET features

I always like it when I come across a nice little feature I find in the .NET Framework.  If I find two in one day, it’s even better.  This is exactly what happened to me yesterday.  We’ll start out with the first feature, actually the only feature I intended to learn about yesterday, the yield keyword.
I use dependency injection on a lot of my projects, including implementing some type of container.  Sometimes I use Unity, sometimes I roll my own.  Regardless of what I use, I end up with a project full of interfaces, including IDataProvider.  For the most part, I end up implementing a MockDataProvider and an XmlDataProvider.  I find this case very common inside of a DataProvider method:
public IEnumerable<IStoredObject> GetStoredObjects()
{
    List<IStoredObject> objects = new List<IStoredObject>();

    foreach (XElement objectElement in XDocument.Elements("Objects"))
    (
        objects.Add(CreateStoredObject(objectElement));
    )

    return objects;
}
This always irritates me to no end because I am just creating this List<> so that I can return these values.  I wish I could just return them.  But alas, you can.
public IEnumerable<IStoredObject> GetStoredObjects()
{
    foreach (XElement objectElement in XDocument.Elements("Objects"))
    (
        yield return CreateStoredObject(objectElement);
    )
}
Bam.  This simple statement will tell the compiler to return something it can enumerate through.  There are other uses for this keyword as well, but for me, I will use this case all of the time.  Here and here are articles with some more information.
Now for part 2.  Coincidentally, this subject was on the next page in a book I was reading to find out about yield, which is why I found out about it. I frequently have need for the ICloneable interface.  There is a well known debate in the development world about this interface.  Some think ICloneable should be a deep clone, some think it should be a shallow clone.  Regardless, all the way down in System.Object, is a protected method called MemberwiseClone.  This does a shallow copy for you.  What?  Yeah, I know.  I had no idea either.  It will copy all of your fields in your class for you and return the object.  Like everything else in .NET, if it’s a value type, you get a copy, if it’s a reference type, you get the same reference.  Pretty sweet.

Share this post!

0 comments:

Post a Comment