views:

133

answers:

2

Given a null cast:

var result = MyMethod( (Foo) null );

Is it possible to use this extra information inside the method with reflection?

EDIT:
The method's signature is something like:

object MyMethod( params object[] args )
{
  // here I would like to see that args[0] is (was) of type Foo
}
+2  A: 

Ahh... you edited...

I suspect the closest you'll get is generics:

object MyMethod<T>( params T[] args ) {...}

(and look at typeof(T))

But that assumes all the args are the same. Other than that; no. Every null is the same as every other (Nullable<T> aside), and you cannot tell the variable type.


Original reply:

Do you mean overload resolution?

object result = someType.GetMethod("MyMethod",
        new Type[] { typeof(Foo) })
        .Invoke(someInstance, new object[] { null });

(where someInstance is null for static methods, and someType is the Type that has the MyMethod method)

Marc Gravell
+1  A: 

Short answer: No

I'm guessing you got something like this:

class Foo : Bar{}

Since you've got:

object MyMethod(param object[] values);

There's no way to do this. You could use a null object pattern to accomplish this:

class Foo : Bar
{
 public static readonly Foo Null=new Foo();
}

and then call with Foo.Null instead of null. Your MyMethod could then check for the static instance and act accordingly:

object MyMethod(param object[] values
{
 if(values[0]==Foo.Null) ......
}
Sean
Thanks for the null object pattern - another idea.
tanascius