The function below returns a type of Dynamic, what is the most efficient way to cast it to IDictionary
public dynamic GetEntities(string entityName, string entityField)
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I’d probably go with the
asoperator.Then do a
nullcheck.UPDATE
In regards to the “efficient” part of your question, I think
asmay be pretty efficient compared to some other paths you could take:IDictionary<string,string>andthen catch the exception, but using exceptions for control flow
isn’t a good idea and is expensive.
expression is type ? (type)expression : (type)null, but in this case, you evaluateexpressiontwice (but you do get a null if the expected type isn’tthe type that expression returns). So you’re doing double
evaluations.
asis only good for reference or boxing conversions, not to perform user-defined conversions, so if you need that, thenasisn’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 useIDictionaryafterasinstead of specifying the generic type parameters. I guess it depends on what you’re expecting.Hope this helps.