DEV Community

Cover image for Reflection In C#: 4 Simple But Powerful Code Examples

Reflection In C#: 4 Simple But Powerful Code Examples

Dev Leader on March 05, 2024

The post Reflection in C#: 4 Code Simple But Powerful Code Examples appeared first on Dev Leader. Reflection in C# is a powerful feature that allo...
Collapse
 
alassane-developer profile image
alassane-developer • Edited

Great !!!
So we can use reflection to test a private method for example? Indeed we often don't need to test private method but just the public caller.
Is it a bad approach?

Collapse
 
devleader profile image
Dev Leader

In my opinion - Yes, this is a very very bad approach. 99% of the time this is absolutely not what you want to be doing.

But I am very glad that you asked this question. If you find that you need to use reflection to test a private method, I would highly suggest you reconsider how your class has been designed. If you truly need unit-test style coverage on a private method and the only way to access it is via other methods, it might be an opportunity to extract this via refactoring and put it onto another dedicated dependency.

In my professional experience, the only times I ever need to use reflection for testing private things:

  • We need to deploy a CRITICAL bug fix in some legacy code. We don't have time to refactor it to test it "properly" but we want to have some confidence that we can test our change to some degree. We might go do something like this to get the confidence we need, and then afterwards reschedule if we need to go back and refactor+test properly.
  • Extreme edge cases trying to test with third party libraries where we don't have access to what we need.

In either of these cases, or in any situation where you're circumventing the access modifiers: You are going against how something was designed to be used. You should expect that this type of code will be extremely brittle due to changes.

I hope that helps! But please let me know if you have any questions!