Question

I have a scenario where I need to check whether a DataContext of a control is implementing "INotifyPropertyChanged" and another interface called "ITObject". The interface "ITObject" is located in some other assembly and the implementing class is called "TObjectBase" which has an event called "TObjectChanged".

We do not add their assemblies to our project but instead they will be adding our assemblies to their projects which we build and give them.

The problem I have is that the only information I have is the textual representation of these class/interface names and nothing more but I need to check at runtime whether the DataContext of the control is implementing these interfaces and hook to the TObjectChanged event and react to it.

I tried using Type.GetType("TObjectBase") to check it, but I require the fully qualified name, isn't it? because they are all located in a different assembly that I don't have any idea of. Also, IsAssignableFrom("ITObject") also fails.

I was wondering if the userbase here could help me with this.

Was it helpful?

Solution

You can load all the active assemblies in the app domain, then walk each assembly's types looking for a name match. Without the assembly name though, you can't use Type.GetType() as you saw.

The following simple program works for me.

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(GetFqTypeName("IMyInterface"));
        Console.ReadKey();
    }

    static String GetFqTypeName(string shortTypeName)
    {
        return AppDomain.CurrentDomain.GetAssemblies()
            .ToList()
            .SelectMany(x => x.GetTypes())
            .Where(x => x.Name == shortTypeName)
            .Select(x => x.FullName)
            .FirstOrDefault();
    }
}

public interface IMyInterface { }

OTHER TIPS

Try the is operator.

if (DataContext is INotifyPropertyChanged && DataContext is ITObject)
{
   // magic
}

You also have IsAssignableFrom backwards.

typeof(ITObject).IsAssignableFrom(DataContext.GetType());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top