Makach
Makach

Reputation: 7569

How to check that object implements interface

Given this scenario

interface A {}

class B : A {}

A b = new B();

How can I check that object b is created from interface A?

Upvotes: 5

Views: 3340

Answers (4)

Pondidum
Pondidum

Reputation: 11627

You could do test it like this:

var b = new B();

var asInterface = x as A;
if (asInterface == null) 
{
    //not of the interface A!
}

Upvotes: 5

user572559
user572559

Reputation:

We found it practical to use the following:

IMyInterface = instance as IMyInterface;
if (intance != null)
{
//do stuff
}

'as' is the faster than 'is', also is saves a number of casts - if your instance impelments IMyInterface, you'll need no more casts.

Upvotes: 0

Lloyd
Lloyd

Reputation: 2942

IS and AS.

Upvotes: 3

Stecya
Stecya

Reputation: 23266

Try to use is

if(b is A)
{
    // do something
}

is that what you want?

Upvotes: 11

Related Questions