5

Given this scenario

interface A {}

class B : A {}

A b = new B();

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

Makach
  • 7,435
  • 6
  • 28
  • 37
  • 2
    What do you mean by "is created from interface A"? You can tell that you can use the value of `b` as a reference to an implementation of `A` by the fact that it's assigned to a variable of type `A`... please clarify your question. – Jon Skeet Mar 01 '11 at 11:06

4 Answers4

11

Try to use is

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

is that what you want?

Stecya
  • 22,896
  • 10
  • 72
  • 102
5

You could do test it like this:

var b = new B();

var asInterface = x as A;
if (asInterface == null) 
{
    //not of the interface A!
}
Pondidum
  • 11,457
  • 8
  • 50
  • 69
3

IS and AS.

Lloyd
  • 2,932
  • 2
  • 22
  • 18
0

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.

  • I'm not so concerned about speed, semantically I think it is more appropriate to use is – Makach Mar 01 '11 at 11:17
  • 1
    @Dmitry - do you have proof links with tests?. Cause i just tried 1000000000 iteration with "is" and "as" and "is" is slightly faster – Stecya Mar 01 '11 at 11:20
  • there you go: http://stackoverflow.com/questions/496096/casting-vs-using-the-as-keyword-in-the-clr, also what're you going to do after Is returns true? Do cast again?:) –  Mar 01 '11 at 11:30
  • 1
    why cast? if it imlements Interface than object must have that methods – Stecya Mar 01 '11 at 11:33
  • Then why check? If it has those methods, just call them :) `Is` and `As` are concerned with the runtime values of the types, so if you need them in the first place, you are not sure what the object is and what it can do. – SWeko Mar 01 '11 at 11:36
  • @Dmitry in link that you provided there is no plain comparison between "is" and "as". If compare `var res = a as B;` and `var res = a is B;` "is" is slightly faster – Stecya Mar 01 '11 at 11:40
  • 2
    @SWeko - "is" and "as" have different purposes. If I want to check if object is of Type, then I should use "is". If I want to get object of that Type than I should use "as". It's 2 differnt situations – Stecya Mar 01 '11 at 11:43
  • 1
    @Stecya - if I just want to check, then use `is`. But if I want to check **and** then use the object as the checked type, using `is` requires using an additional `as` or an explicit cast. And you are right about the speed being a non-issue here. – SWeko Mar 01 '11 at 11:47