8

Question

I am trying to dynamically get the default for a type that is specified in a ParameterInfo. _methods[methodName] returns a MethodInfo object.

Unfortunately, the compiler doesn't like the "paramType" bit inside the default(paramType). I'm stumped.

Error

The type or namespace name 'paramType' could not be found (are you missing a using directive or an assembly reference?)

C:\Applications\...\MessageReceiver.cs Line 113

Example

object blankObject = null;
foreach (var paramInfo in _methods[methodName].Key.GetParameters())
{
    if (paramInfo.Name == paramName)
    {
        Type paramType = paramInfo.ParameterType;
        blankObject = (object)default(paramType);
    }
}
parameters[i] = blankObject;
Community
  • 1
  • 1
Chris Benard
  • 3,167
  • 2
  • 29
  • 35

2 Answers2

28

It's quite simple to implement:

public object GetDefault(Type type)
{
    return type.IsValueType ? Activator.CreateInstance(type) : null;
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

I think default only works with the an actual type. It's a complier shortcut not an actual method. It works well with generics. for example:

public void MyMethod<T>(T obj)
{
   T myvar = default(T);
}

Check out this question I posted a while back:

Default Value for Generics

Community
  • 1
  • 1
Micah
  • 111,873
  • 86
  • 233
  • 325
  • 1
    Right... I've used it with generics a lot, but now I need to get it from a ParameterInfo. Surely there is a way to do this through reflection or something. – Chris Benard Jan 23 '09 at 22:24