Reflections on Reflection
Hey all!
This is me posting from the beautiful city of London, UK!
So far 55 pictures, but that's not what I wanted to talk about (but my next posts will all come with a London pic, that's how much I like this city).

I've did some pretty wicked stuff with reflection in the course of my .Net career, both in .Net 1.1 and 2.0. I've built an ORM heavily based in reflection, I did NMVP that uses it as well as I did a Mocking engine specialized in mocking views for NMVP.
After finishing the Build Breaking Changes plug-in (next post) I found out that I didn't know as much reflection as I thought. But instead of telling you, I'll let you try to score.
Reflection Trivia
First question
If I have a class with the following code:
1: public class TestClass{
2: public string TestProperty{
3: get{
4: //return some stuff.
5: }
6: set {
7: //set some stuff.
8: }
9: }
10:
11: public event EventHandler TestEvent;
12:
13: public void TestMethod1(){
14: //Do Stuff.
15: }
16:
17: public void TestMethod2(){
18: //Do Stuff.
19: }
20: }
The question is how many MethodInfo objects this code returns:
typeof(TestClass).GetMethods();
Second question
Consider the following class:
1: public class TestClass{
2: public enum TestEnum{
3: someValue = 0,
4: someValue = 1
5: }
6:
7: public class MyNestedClass{
8: public class MyTwofoldNestedClass{
9:
10: }
11: }
12: }
What do you need to pass as a parameter to Type.GetType (or Assembly.GetType) to get TestEnum? And MyNestedClass? and MyTwofoldNestedClass? (What is the full name?).
Third question
Considering the same class in the example before, assuming you've got the correct Type object. What does the IsPublic property return in each case? Why?
1: Type enumType = Type.GetType(enumFullName);
2:
3: Assert.AreEqual(?, enumType.IsPublic);
What does the ? stands for in each of the three cases (TestEnum, MyNestedClass, MyTwofoldNestedClass)? And why?
Fourth question
What's wrong with the following code:
1: public class TestClass{
2: public enum TestEnum{
3: TestValue,
4: TestValue2
5: }
6:
7: public struct TestStruct{
8:
9: }
10:
11: public interface ITestInterface{
12:
13: }
14:
15: public class NestedClass{
16:
17: }
18: }
19:
20: //Later on, I write this code.
21:
22: Type classType = Type.GetType ("TestClass"); //assume this is the correct fullname.
23: foreach(Type sub in classType.GetTypes()){
24: if (sub.IsEnum){
25: enums.Add(sub);
26: }
27: if (sub.IsInterface){
28: interfaces.Add(sub);
29: }
30: if (sub.IsClass){
31: classes.Add(sub);
32: }
33: if (sub.IsValueType){
34: structs.Add(sub);
35: }
36: }
And how do we fix it?
Conclusion
I'll answer them all in my next post, where I'll talk more about the plug-in that's already built!
#128