Search code examples
c#interfacepolymorphismderived-class

How to check if an object is derived from an interface?


I have some classes that are derived from an interface, and I would like to be able to check in code to see if an object that is passed in is derived from that interface, but im not sure exactly the method calls ...

interface IFile
{
}

class CreateFile : IFile
{
    string filename;
}

class DeleteFile : IFile
{
    string filename;
}

// Input here can be a string or a file
void OperateOnFileString( object obj )
{
    Type theType = obj.GetType();

    // Trying to avoid this ...
    // if(theType is CreateFile || theType is DeleteFile)

    // I dont know exactly what to check for here
    if( theType is IFile ) // its not, its 'CreateFile', or 'DeleteFile'
        print("Its an IFile interface");
    else
        print("Error: Its NOT a IFile interface");
}

In actuality I have hundreds of derived classes from that interface and i'm trying to avoid having to check for each type, and having to add the check when I create another class from that type.


Solution

  • is is exactly correct.
    However, you need to check the instance itself.

    obj.GetType() returns an instance of the System.Type class that describes the object's actual class.

    You can just write if (obj is IFile).