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

Extension method syntax in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
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 StringExtensions
Inside it, create a public static method called Greet that extends string
The Greet method should return a string formatted as "Hello, {original string}!"
Use the Greet method on a string variable called name
Print 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
1
Create a string variable
Create a string variable called name and set it to the value "Alice".
C Sharp (C#)
Need a hint?

Use string name = "Alice"; to create the variable.

2
Create a static class for extension methods
Create a public static class called StringExtensions to hold extension methods.
C Sharp (C#)
Need a hint?

Use public static class StringExtensions { } to create the class.

3
Add the extension method Greet
Inside the StringExtensions class, create a public static method called Greet that extends string using the this keyword. The method should return a string formatted as "Hello, {original string}!".
C Sharp (C#)
Need a hint?

Use public static string Greet(this string str) and return the greeting with $"Hello, {str}!".

4
Use the extension method and print the result
Call the Greet method on the name variable and print the result using Console.WriteLine.
C Sharp (C#)
Need a hint?

Use Console.WriteLine(name.Greet()); to print the greeting.