0

I can use HasProperty to check if a property exists. Only if the property exists a method should be executed.

How can the compiler successfully compile even if the property doesn't exist? E.g.

if (UIApplication.SharedApplication.Delegate.HasProperty("Instance"))
{
    AppDelegate customAppDelegate = UIApplication.SharedApplication.Delegate as AppDelegate;
    customAppDelegate.Instance.SomeMethod(true); // can't be compiled because Instance doesn't exist
}

The thing is this: First, I check if the propery exists. If yes I execute my method. So normally the code is never executed (except the property exists), but the compiler isn't able to differentiate this. It only checks if the property exists and doesn't take the if clause into account.

Is there a solution for this?

Community
  • 1
  • 1
testing
  • 19,681
  • 50
  • 236
  • 417
  • 3
    Use reflection to execute the method or cast it to a `dynamic`. – DavidG Nov 23 '15 at 14:00
  • I can't find methods like `GetMethod()`. I think they are not available in my runtime environment. – testing Nov 23 '15 at 14:06
  • Then cast it to `dynamic`. – DavidG Nov 23 '15 at 14:06
  • Can you perhaps post an example? If I try to cast it to `dynamic` I get *Error CS1969: Dynamic operation cannot be compiled without `Microsoft.CSharp.dll' assembly reference (CS1969)*. – testing Nov 23 '15 at 14:22
  • I meant: `dynamic customAppDelegate = .....`. If that gives the same error, then add a reference to `Microsoft.CSharp`. – DavidG Nov 23 '15 at 14:23
  • If you can't include the `Microsoft.CSharp.dll` file, then you will have to invoke it through reflection. You can't just check for the existence of a property (if statements are **runtime** remember) and then use it like a normal compile-time operation. – Ron Beyer Nov 23 '15 at 14:24

1 Answers1

0

You have to include the reference to Microsoft.CSharp to get this working and you need using System.Reflection;. This is my solution:

if(UIApplication.SharedApplication.Delegate.HasMethod("SomeMethod"))
{
    MethodInfo someMethodInfo = UIApplication.SharedApplication.Delegate.GetType().GetMethod("SomeMethod");
    // calling SomeMethod with true as parameter on AppDelegate
    someMethodInfo.Invoke(UIApplication.SharedApplication.Delegate, new object[] { true });
}

Here is the code behind HasMethod:

public static bool HasMethod(this object objectToCheck, string methodName)
{
    var type = objectToCheck.GetType();
    return type.GetMethod(methodName) != null;
} 

Thanks to DavidG for helping me out with this.

Community
  • 1
  • 1
testing
  • 19,681
  • 50
  • 236
  • 417