Clear, practical technology insights About · Contact

Reflection in C #: Explained

Understand Reflection in C # with clear explanations, practical examples, and useful tips. This updated guide covers the essential concepts and common mistakes.

Published: 6 minutes read
Table of Contents

Reflection in C # is easier to understand when the core ideas are paired with practical examples. The sections below explain the topic clearly, highlight useful steps, and point out details that can prevent common errors.

Reflection objects help obtain type information at runtime. These classes provide access to the program's metadata running in the System.Reflection namespace in C #.

In C # Namespace System.Reflection contains classes that allow you to obtain information about the application and to dynamically add types, values, and objects to the Application.

The application of Reflection

The MemberInfo object of the System.Reflection class in C # needs to be initialized to detect the attributes associated with a class. To do this, you define an object of the target class, like:

 System . Reflection . MemberInfo info = typeof ( MyClass ); 

the example below illustrates this: creating 3 classes named HelpAttribute, MyClass, and Tester respectively :

 using System ; namespace VdMetadata { [ AttributeUsage ( AttributeTargets . All )] public class HelpAttribute : System . Attribute { public readonly string Url ; public string Topic // Topic la mot name parameter 
 { get { return topic ; } set { topic = value ; } } public HelpAttribute ( string url ) // url la mot positional parameter 
 { this . Url = url ; } private string topic ; } [ HelpAttribute ( "Thông tin của lớp MyClass" )] class MyClass { 
 } class Tester { static void Main ( string [] args ) { Console . WriteLine ( "Reflection trong C#" ); Console . WriteLine ( "--------------------------" ); System . Reflection . MemberInfo info = typeof ( MyClass ); object [] attributes = info . GetCustomAttributes ( true ); for ( int i = 0 ; i < attributes . Length ; i ++) { System . Console . WriteLine ( attributes [ i ]); } Console . ReadKey (); } } } 

Compiling and running the C # program on you will get the results:

 Reflection in C # 
 -------------------------- 
 VdMetadata.HelpAttribute 

For example

In this example, we use the attribute DeBugInfo created in the previous lesson and use Reflection to read the metadata in the Rectangle class.

 using System ; using System . Reflection ; namespace QTMCSharp { // BugFix được gán cho lớp và thành viên của nó [ AttributeUsage ( AttributeTargets . Class | AttributeTargets . Constructor | AttributeTargets . Field | AttributeTargets . Method | AttributeTargets . Property , AllowMultiple = true )] public class DeBugInfo : System . Attribute { private int bugNo ; private string developer ; private string lastReview ; public string message ; public DeBugInfo ( int bg , string dev , string d ) { this . bugNo = bg ; this . developer = dev ; this . lastReview = d ; } public int BugNo { get { return bugNo ; } } public string Developer { get { return developer ; } } public string LastReview { get { return lastReview ; } } public string Message { get { return message ; } set { message = value ; } } } 
 [ DeBugInfo ( 45 , "Nguyễn Huy" , "03/09/2017" , Message = "Kiểu trả về không hợp lệ" )] [ DeBugInfo ( 49 , "Hà Minh" , "09/11/2017" , Message = "Biến chưa được sử dụng" )] class Rectangle { //các biến thành viên protected double dai ; protected double rong ; public Rectangle ( double d , double r ) { dai = d ; rong = r ; } [ DeBugInfo ( 55 , "Nguyễn Huy" , "03/09/2017" , Message = "Kiểu trả về không hợp lệ" ) ] public double tinhS () { return dai * rong ; } [ DeBugInfo ( 56 , "Hà Minh" , "09/11/2017" ) ] public void Display () { Console . WriteLine ( "Chiều dài: {0}" , dai ); Console . WriteLine ( "Chiều rộng: {0}" , rong ); Console . WriteLine ( "Diện tích: {0}" , tinhS ()); } } //Hết lớp Rectangle 
 class ExecuteRectangle { static void Main ( string [] args ) { Rectangle r = new Rectangle ( 4.5 , 7.5 ); r . Display (); Type type = typeof ( Rectangle ); //lặp qua các thuộc tính của lớp Rectangle. foreach ( Object attributes in type . GetCustomAttributes ( false )) { DeBugInfo dbi = ( DeBugInfo ) attributes ; if ( null != dbi ) { Console . WriteLine ( "Mã lỗi: {0}" , dbi . BugNo ); Console . WriteLine ( "Nhà phát triển: {0}" , dbi . Developer ); Console . WriteLine ( "Xem lần cuối: {0}" , dbi . LastReview ); Console . WriteLine ( "Ghi chú: {0}" , dbi . Message ); } } // lặp qua các thuộc tính của phương thức. foreach ( MethodInfo m in type . GetMethods ()) { foreach ( Attribute a in m . GetCustomAttributes ( true )) { DeBugInfo dbi = ( DeBugInfo ) a ; if ( null != dbi ) { Console . WriteLine ( "Bug no: {0}, for Method: {1}" , dbi . BugNo , m . Name ); Console . WriteLine ( "Developer: {0}" , dbi . Developer ); Console . WriteLine ( "Last Reviewed: {0}" , dbi . LastReview ); Console . WriteLine ( "Remarks: {0}" , dbi . Message ); } } } Console . ReadLine (); } } } 

Compiling and running the above C # program will produce the following results:

 Length: 4.5 
 Width: 7.5 
 Area: 33.75 
 Error code: 45 
 Developer: Nguyen Huy 
 See last time: September 3, 2017 
 Note: The return type is invalid 
 Error code: 49 
 Developer: Ha Minh 
 Last viewed: November 9, 2017 
 Note: The variable has not been used 
 Bug no: 55, for Method: tinhS 
 Developer: Nguyen Huy 
 Last Reviewed: September 3, 2017 
 Remarks: Invalid return type 
 Bug no: 56, for Method: Display 
 Developer: Ha Minh 
 Last Reviewed: November 9, 2017 
 Remarks: 

Frequently Asked Questions

What should you know about the application of Reflection?

The MemberInfo object of the System.Reflection class in C # needs to be initialized to detect the attributes associated with a class. To do this, you define an object of the target class, like:

What is Reflection in C #?

Reflection objects help obtain type information at runtime.

Why is Reflection in C # important?

A clear understanding of Reflection in C # helps you make informed decisions, avoid common mistakes, and use the relevant tools or techniques more effectively.

Was this article helpful?

Your feedback helps us improve.

Discussion

Reader Comments 0

Sign in with email or Google to join the discussion.