EDIT: Oops - as rightly pointed out, there'd be no way to know whether the constructor for the class in question is sensitive to when or how many times it is called, or whether the object's state is changed during the method, so it would have to be created from scratch each time. Ignore the Dictionary and just consider delegates created in-line during the course of a method :-)
Say I have the following method with Dictionary of Type to Action local variable.
void TakeAction(Type type)
{
// Random types chosen for example.
var actions = new Dictionary<Type, Action>()
{
{typeof(StringBuilder), () =>
{
// ..
}},
{typeof(DateTime), () =>
{
// ..
}}
};
actions[type].Invoke();
}
The Dictionary will always be the same when the method is called. Can the C# compiler notice this, only create it once and cache it somewhere for use in future calls to the method? Or will it simply be created from scratch each time? I know it could be a field of the containing class, but it seems neater to me for a thing like this to be contained in the method that uses it.