Easy way to check if object implements a specific interface

by Shannon Deminick 21. December 2009 04:56

Here’s a quick little snippet of how to check if one of your objects implements a specific interface. I’m not sure if there’s a ‘better’, or more efficient way to do this but I’ve been using this method to do this check for quite some time:

if (typeof(IMyInterface).IsAssignableFrom(myObject.GetType()))
{
	//Do stuff...
}

UPDATE:

Turns out there is a way easier and probably much more efficient way of doing this! I just didn't know it worked with interfaces too

if (myObject is IMyInterface) { //Do Stuff.. }

Much nicer!

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

.Net

Add comment


 
  Country flag

biuquote
  • Comment
  • Preview
Loading

Prove that you are a human and not a spambot...
What is "The Meaning of Life, The Universe, and Everything", minus -3, then added to
CAPTCHA number





// Website built by The FARM