Reputation: 840
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.
Upvotes: 2
Views: 6207
Reputation: 102753
You could use BaseType
:
if (type.BaseType is file)
Since file
is an interface, use Type.GetInterfaces to check the underlying interfaces of type
:
if (type.GetInterfaces().Any(i => i.Equals(typeof(file))
Or probably a bit faster, use Type.GetInterface:
if (type.GetInterface(typeof(file).FullName) != null)
(This searches the interfaces of type
and of any inherited classes or interfaces.)
Upvotes: 2
Reputation: 7774
is
operator works or you can do:
if (someInstance is IExampleInterface) { ... }
or
if(typeof(IExampleInterface).IsAssignableFrom(type)) {
...
}
Upvotes: 6
Reputation: 6612
you can create an extension method like below
/// <summary>
/// Return true if two types or equal, or this type inherits from (or implements) the specified Type.
/// Necessary since Type.IsSubclassOf returns false if they're the same type.
/// </summary>
public static bool IsSameOrSubclassOf(this Type t, Type other)
{
if (t == other)
{
return true;
}
if (other.IsInterface)
{
return t.GetInterface(other.Name) != null;
}
return t.IsSubclassOf(other);
}
and use it like below
Type t = typeof(derivedFileType);
if(t.IsSameOrSubclassOf(typeof(file)))
{ }
Upvotes: 1
Reputation: 437376
You are passing the wrong argument to is
. The correct is
if (obj is file) {
// ...
}
However it would be even better if you had an overload of the method that directly accepts a file
parameter. In fact it's quite unclear how one that accepts an object
could efficiently use it.
Upvotes: 3
Reputation: 887453
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)
.
Upvotes: 8