Create and Use an Extension Method in C#
📖 Scenario: Imagine you want to add a new feature to the string type in C# without changing its original code. You will create an extension method that adds a simple greeting to any string.
🎯 Goal: Build a C# program that defines an extension method called Greet for the string type. This method will return a greeting message using the original string. Then, use this method on a string variable and print the result.
📋 What You'll Learn
Create a static class called
StringExtensionsInside it, create a public static method called
Greet that extends stringThe
Greet method should return a string formatted as "Hello, {original string}!"Use the
Greet method on a string variable called namePrint the result of calling
name.Greet()💡 Why This Matters
🌍 Real World
Extension methods let you add new features to existing types without changing their original code. This is useful when working with libraries or built-in types.
💼 Career
Many C# developers use extension methods to write cleaner, more readable code and to add helpful utilities to existing types.
Progress0 / 4 steps