Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If reflection is inefficient, when is it most appropriate?

Tags:

c#

reflection

I find a lot of cases where I think to myself that I could use relfection to solve a problem, but I usually don't because I hear a lot along the lines of "don't use reflection, it's too inefficient".

Now I'm in a position where I have a problem where I can't find any other solution than to use reflection with new T(), as outlined in this question & answer.

So I'm wondering if somebody can tell me reflection's specific intended usage, and if there's a set of guidelines to indicate when it's appropriate and when it isn't?

like image 739
DaveDev Avatar asked Jul 31 '10 09:07

DaveDev


Video Answer


2 Answers

It is often "fast enough", and if you need faster (for tight loops etc) you can do meta-programming with Expression or ILGenerator (perhaps via DynamicMethod), to make extremely fast code (including some tricks you can't do in C#).

Reflection is more commonly used for framework/library scenarios, where the library by definition knows nothing about the caller, and must work based on configuration, attributes or patterns.

like image 126
Marc Gravell Avatar answered Nov 07 '22 18:11

Marc Gravell


If there's one thing that I hate hearing it's "don't use reflection, it's too inefficient".

Too inefficient for what? If you're writing a console application that's run once a month and isn't time critical, does it really matter if it takes 30 seconds instead of 28, because of you using reflection?

Guidelines for when it's inappropriate to use are ones that only you can really put together as they're heavily dependent on what you're doing and how efficient/performant alternatives are.

like image 36
Rob Avatar answered Nov 07 '22 19:11

Rob