I'd probably go with the as
operator.
var result = GetEntities("blah", "blahblah") as IDictionary<string,string>;
Then do a null
check.
UPDATE
In regards to the "efficient" part of your question, I think as
may be pretty efficient compared to some other paths you could take:
- You could just blindly cast it to
IDictionary<string,string>
and then catch the exception, but using exceptions for control flow isn't a good idea and is expensive. - You could use a convention like
expression is type ? (type)expression : (type)null
, but in this case, you evaluateexpression
twice (but you do get a null if the expected type isn't the type that expression returns). So you're doing double evaluations. as
is only good for reference or boxing conversions, not to perform user-defined conversions, so if you need that, thenas
isn't for you.
See this article on MSDN.
UPDATE 2
I made an assumption on the key/value types of the IDictionary
. You could just use IDictionary
after as
instead of specifying the generic type parameters. I guess it depends on what you're expecting.
Hope this helps.