Monday 13 February 2012

Downcasting Using Dynamics- C#

A few days ago I learned something new. 

For certain unfortunate reasons sometimes one is forced to downcast an object before sending it to a method which takes a generic parameter. Again, this isn't an ideal case as it seems less generic, but just in case someone else has found themselves in such a pickle because of other constraints, I hope you find this solution as helpful as I have. In C# 4.0 the dynamic was introduced.



Given a couple of tools that inherit from a tool object:



public abstract class Tool {
}
public class Wrench : Tool {
}
public class ScrewDriver : Tool {
}

And a method that takes the generic:


public class ToolHandler {
    public virtual void Tighten<T>(T tool) {
    }
}


How does one downcast the object from a list before calling the method without checking each type in a list?


public List<Tool> Tools { get; set; }

var _toolHandler = new ToolHandler();
List<Tool> tools = new List<Tool>{new Wrench(), new ScrewDriver()};



*************Former sloppy way******************

foreach(var tool in tools){
    if (tool is Wrench) {
        _toolHandler.Tighten((Wrench)tool);
    }
    if (tool is ScrewDriver) {
        _toolHandler.Tighten((ScrewDriver)tool);
    }
}    

****************************************************

The answer- use a dynamic. 

foreach(var tool in tools){
    _toolHandler.Tighten((dynamic)tool);
}


*Special thanks to M.Babcock on stackoverflow for answering my co-worker's and my question. http://stackoverflow.com/questions/9116034/downcast-instance-using-its-type

Feel free to paste this inside Rextester (http://rextester.com/runcode) or wherever you would like to run it for an example. Hopefully the link still works too http://rextester.com/live/IJWT40081.



using System;
using System.Collections.Generic;

namespace Rextester
{
    public class Program
    {
        public abstract class Tool {
        }
        public class Wrench : Tool {
        }
        public class ScrewDriver : Tool {
        }
        public class ToolHandler {
            public virtual void Tighten<T>(T tool) {
                Console.WriteLine(typeof(T));
            }
        }
   
        public static void Main(string[] args)
        {
            List<Tool> tools = new List<Tool>{new Wrench(), new ScrewDriver()};
       
            var handler = new ToolHandler();
            foreach(var tool in tools){
                handler.Tighten((dynamic)tool);
            }
        }
    }
}

Rextester - Neat way to run C# code online

http://rextester.com/runcode

See next post for example.

Friday 10 February 2012

A Soap Holder Worth Mentioning

Vertical Soap holder 

Maybe these things are more popular than I think, but it's new to me so I thought I'd mention it. What a great invention. I found it in the corporate apartment I've been staying in. I know bar soap isn't as popular with so many liquid/gel body wash options out there, but it's still the classical cheaper solution to get yourself clean. Unfortunately, sometimes those bars don't last as long as they should when they sit in water 24/7. This creation holds your soap bar in an isolated vertical position that allows the water to constantly roll off the majority of surface area. For an extra effect, you can hang it outside of the shower head drip/spray direction.

Under 100 Calories Squawk

90 calorie granola bar in what appears to be it's former full breakfast bar's wrapper


Low calorie food options have become very popular as of lately. For multiple reasons, I am usually happy about this. If you can make the same dish at a restaurant with half as much goose fat, butter, or whatever your favorite lard choice is, great! *(Assuming they are not substituting it with something worse). In general, people don't need as much fat. However, like every fad, it has been taken to a bit of extreme. I feel like some companies are loving the fact they can put half as much food in a wrapper; label it as a healthy food option because it has lower calories; and then sell it for the same price. The recipe hasn't changed. When I purchase food to bring home, I'm paying for a quantity of the substance. That quantity happens to be measured in calories. Now I'm stuck buying twice as many and buried under 3' of wrappers. What happened to the '25% more' marketing fad?