0
0
C Sharp (C#)programming~30 mins

Inspecting methods and properties in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Inspecting methods and properties
📖 Scenario: Imagine you have a simple class representing a car. You want to learn how to look inside this class to see what methods and properties it has. This is useful when you want to understand or use a class without reading all its code.
🎯 Goal: You will create a class called Car with some properties and methods. Then, you will write code to inspect and list all the methods and properties of the Car class using reflection.
📋 What You'll Learn
Create a class Car with properties and methods
Create a variable to hold the Type of the Car class
Use reflection to get all methods and properties of the Car class
Print the names of all methods and properties
💡 Why This Matters
🌍 Real World
Inspecting methods and properties helps developers understand and use classes from libraries or frameworks without reading all the source code.
💼 Career
Reflection is useful in debugging, building tools, and frameworks that need to work with unknown or dynamic types at runtime.
Progress0 / 4 steps
1
Create the Car class with properties and methods
Create a class called Car with two public properties: Make of type string and Year of type int. Also add a public method called StartEngine that returns void and has no parameters.
C Sharp (C#)
Need a hint?

Use public class Car to start the class. Add properties with public string Make { get; set; } and public int Year { get; set; }. Add a method public void StartEngine().

2
Get the Type object for the Car class
Create a variable called carType and set it to the Type of the Car class using typeof(Car).
C Sharp (C#)
Need a hint?

Use Type carType = typeof(Car); to get the type information of the Car class.

3
Use reflection to get methods and properties
Create two variables: methods and properties. Set methods to carType.GetMethods() and properties to carType.GetProperties().
C Sharp (C#)
Need a hint?

Use carType.GetMethods() to get all methods and carType.GetProperties() to get all properties.

4
Print the names of all methods and properties
Use a foreach loop to print the name of each method in methods and each property in properties. Use Console.WriteLine to print each name.
C Sharp (C#)
Need a hint?

Use foreach (var method in methods) { Console.WriteLine(method.Name); } and similarly for properties.