Skip to content

Day 04 Reflection

Kobi Hari edited this page Sep 17, 2020 · 1 revision

Day 04 - Reflection

Projects:

Fun With Reflection Deep Dive into the Reflection

Reflection Basics

  • We have seen how to get the type object from an instance using GetType() or from type using typeof
  • We have seen how to query the members of the type: Properties, Methods, Fields, and Events
  • We used the Is**** properties to query specific aspects of a member such as access level, static or not, and so on.
  • We have seen how to invoe a method using reflection MethodInfo
  • We have seen how to set the value of a property using PropertyInfo
  • We have seen how to instantiate an object using the Activcator

Reflection Generics

  • We have defined the difference between an Open Type (A.K.A Generic Type Definition) and a Closed Type
  • We saw how to extract the Type object for open and closed types
  • We have seen how to get the open type from a closed type using Type.GetGenericTypeDefinition()
  • We have seen how to generate a closed type from an open type using Type.MakeGenericType and providing the type arguments

Attributes

  • We have seen how to use the [CallerMemberName] attribute to get the name of the calling method as parameter to another method
  • We created a new custom attribute by inheriting a class from the Attribute base class
  • We used the AttributeUsage attribute to define where our attribute may be used
  • We defined alternative constructors for our custom attribute to accept additional data into the attribute instance
  • We used the Type.GetCustomAttributes<T> method to query the attributes that were placed on a method and check if a method is decorated with an attribute

Reflection Performance

  • We explained that method invokation through reflection is expensive
  • We have seen a way to create a compiled delegate from a MethodInfo in order to speed the method invokation on repeating invokations
  • We created a benchmark that compared method invokation through reflection to methd invokation through delegate and found that delegate invokation is about 3 times faster.