Reflection SoftUni Team Technical Trainers C# OOP Advanced Software University http://softuni.bg
Table of Contents What? Why? Where? When? Reflection API Type Class * Table of Contents What? Why? Where? When? Reflection API Type Class Reflecting Fields Reflecting Constructors Reflecting Methods (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
Questions sli.do #CSharp-OOP
Reflection What? Why? Where? When?
What is Metaprogramming? Programming technique in which computer programs have the ability to treat other programs as their data Programs can be designed to: Read Generate Analyze Transform Modify itself while running.
What is Reflection? The ability of a programming language to be it’s own metalanguage Programs can examine information about itself
Why, Where Reflection? Code becomes more extendible Reduces code length significantly Easier maintenance Testing Tools for programmers
When Reflection? If it is possible to perform an operation without using reflection, then it is preferable to avoid using it Cons from using Reflection Performance overhead Security restrictions Exposure of internals
Reflecting Class and Members Reflection API Reflecting Class and Members
You need fully qualified class name as string Type Class Primary way to access metadata Obtain at compile time if you know it’s name Obtain at run time if the name is unknown Type myType = typeof(ClassName); Type is the root of the System.Reflection functionality and is the primary way to access metadata. Use the members of Type to get information about a type declaration, about the members of a type (such as the constructors, methods, fields, properties, and events of a class), as well as the module and the assembly in which the class is deployed. Type describes data types. It stores type information in a variable, property or field. The Type class represents the program's metadata, which is a description of its structure but not the instructions that are executed. Type myType = Type.GetType("Namespace.ClassName") You need fully qualified class name as string © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
Class Name Obtain Class name Fully qualified class name - Type.FullName Class name without the package name - Type.Name string fullName = typeOf(SomeClass).FullName; string simpleName = typeOf(SomeClass).Name; © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
Base Class and Interfaces Obtain base class Obtain interfaces Only the interfaces specifically declared implemented by a given class are returned Type baseType = testClass.BaseType; Type[] interfaces = testClass.GetInterfaces(); © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
New Instance CreateInstance - creates an instance of a type by invoking the constructor that best matches the specified arguments Type sbType = Type.GetType("System.Text.StringBuilder"); StringBuilder sbInstance = (StringBuilder) Activator.CreateInstance(sbType); StringBuilder sbInstCapacity = (StringBuilder)Activator .CreateInstance(sbType, new object[] {10}); https://msdn.microsoft.com/en-us/library/wccyzw83(v=vs.110).aspx © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
Reflect Fields Obtain public fields Obtain all fields FieldInfo field = type.GetField("name"); FieldInfo[] publicFields = type.GetFields(); FieldInfo[] allFields = type.GetFields( BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
Field Type and Name Get field name and type FieldInfo field = type.GetField("fieldName"); string fieldName = field.Name; Type fieldType = field.FieldType; © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
Field Altering Type testType = typeof(Test); Test testInstance = (Test) Activator.CreateInstance(testType); FieldInfo field = testType.GetField("testInt"); field.SetValue(testInstance, 5); int fieldValue = (int) field.GetValue(testInstance); WARNING: use with extreme caution as you could alter an objects internal state! © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
Access Modifiers Each modifier is a flag bit that is either set or cleared Check access modifier of a member of the class field.IsPrivate //private field.IsPublic //public field.IsNonPublic //everything but public field.IsFamily //protected field.IsAssembly //internal etc… IsPrivate – check if field is © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
Reflect Constructors Obtain constructors Obtain all non static constructors ConstructorInfo[] publicCtors = type.GetConstructors(); ConstructorInfo[] allNonStaticCtors = type.GetConstructors( BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
Reflect Constructors(2) Obtain a certain constructor Get parameters type ConstructorInfo constructor = type.GetConstructor(new Type[] parametersType); Type[] parameterTypes = constructor.GetParameters(); © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
Instantiating Objects Instantiating objects using constructor StringBuilder builder = (StringBuilder)constructor.Invoke(new object[] params); Supply an array of object parameters for each argument in the constructor you are invoking The .Invoke method takes an array of objects and you must supply exactly one parameter per argument in the constructor you are invoking. In this case it was a constructor taking a string, so one string must be supplied. © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
Reflect Methods Obtain public methods Obtain certain method MethodInfo[] publicMethods = sbType.GetMethods(); MethodInfo appendMethod = sbType.GetMethod("Append"); MethodInfo overloadMethod = sbType.GetMethod( "Append", new []{typeof(string)}); © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
Method Invoke Obtain method parameters and return type Invoke methods ParameterInfo[] appendParameters = appendMethod.GetParameters(); Type returnType = appendMethod.ReturnType; Parameters for the method appendMethod.Invoke( builder, new object[] { "hi!“ }); Target object instance © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
Live Exercises in Class (Lab) Reflection Live Exercises in Class (Lab) © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
Summary What are the: Benefits Drawbacks Of using reflection? Main benefit: code becomes easy to extend and maintain because it adapts at runtime Main drawback: - performance is sacrificed
Reflection https://softuni.bg/courses/ © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
License This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" license © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
Trainings @ Software University (SoftUni) Software University – High-Quality Education, Profession and Job for Software Developers softuni.bg Software University Foundation softuni.org Software University @ Facebook facebook.com/SoftwareUniversity Software University Forums forum.softuni.bg © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.