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

Extension methods for built-in types in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Extension Methods for Built-in Types
📖 Scenario: Imagine you want to add a new helpful action to a built-in type in C#. For example, you want to add a way to check if a number is even or odd directly on the number itself.
🎯 Goal: You will create an extension method for the built-in int type that checks if a number is even. Then you will use this method to print whether some numbers are even or not.
📋 What You'll Learn
Create a static class called IntExtensions
Inside it, create a public static method called IsEven that extends int
The IsEven method returns true if the number is even, otherwise false
Use the IsEven method on some numbers and print the results
💡 Why This Matters
🌍 Real World
Extension methods let you add new features to existing types without changing their code. This is useful when working with built-in types or libraries you cannot modify.
💼 Career
Knowing how to write extension methods is important for C# developers to write clean, reusable, and readable code that extends functionality in a natural way.
Progress0 / 4 steps
1
Create a static class for extension methods
Create a public static class called IntExtensions to hold extension methods.
C Sharp (C#)
Need a hint?
Extension methods must be inside a static class.
2
Add an extension method IsEven for int
Inside the IntExtensions class, create a public static method called IsEven that extends int using this int number as the first parameter. The method should return true if number % 2 == 0, otherwise false.
C Sharp (C#)
Need a hint?
Use the this keyword before the first parameter to make it an extension method.
3
Use the IsEven extension method on some numbers
In the Main method, create an int variable called num and set it to 4. Then use num.IsEven() to check if it is even and store the result in a bool variable called result.
C Sharp (C#)
Need a hint?
Call the extension method like a normal method on the variable.
4
Print the result of the IsEven check
Add a Console.WriteLine statement to print "4 is even: " followed by the value of result.
C Sharp (C#)
Need a hint?
Use string interpolation with $ and curly braces to include variables in the output.