Ben Voigt [C++ MVP] <(E-Mail Removed)> wrote:
> > Note that this is fairly slow. If you need to do this lots, you're better
> > doing it 'properly' (checking to see if you've got a value or reference
> > type and returning Activator.CreateInstance(type) or null.
>
> If you're going to do this lots, construct an appropriate delegate "delegate
> object ObjectReturnerDelegate()" from the MethodInfo or ConstructorInfo and
> cache this in a Dictionary<Type,ObjectReturnerDelegate>
>
> A delegate call is much faster than reflection.
Except that you've got to use reflection to *get* the method call in
the first place. Rather than caching a delegate, it makes more sense
(IMO) to cache the actual value - and only for value types, at that:
// Thread-safety not shown here
static readonly Dictionary<Type,object> cache =
new Dictionary<Type,object>();
static object GetDefaultValue(Type t)
{
if (!t.IsValueType)
{
return null;
}
object ret;
if (cache.TryGetValue(t, out ret))
{
return ret;
}
ret = Activator.CreateInstance(t);
cache[t] = ret;
return t;
}
--
Jon Skeet - <(E-Mail Removed)>
http://www.pobox.com/~skeet Blog:
http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too