Result
For more understanding, view the below image.
Invoke in Different Namespace
Now, we will see how to call the other namespace extension method in our class. Shall we move? For that, I am going to create one class library in the same solution.
Step 1
Create a new class library in the same solution.
Step 2
Create Extension Method(s)
Here, I have created an extension method to change the first char to uppercase from a given string.
- public static class Class1 {
- public static string FirstCharToUpper(string input) {
- if (String.IsNullOrEmpty(input)) {
- throw new ArgumentException("ArgumentException");
- }
- return input.First().ToString().ToUpper() + input.Substring(1);
- }
- }
Step 3
Refer to the class library into your class. Right click on the respective class to add the extension method class reference.
Step 4
Select Respective Class Library
Here, we are adding the saying that as we are selecting the reference from within the solution.
In the below image, you can see that the HereExtensionMethodExist class library is added as reference to our respective class.
Okay! now let's see how to call the invoke the extenstion method action into our class
Step 1
Add a namespace in header
- using HereExtensionMethodExist;
Step 2
We don't need to create object or we cannot create object for extension method
-
- Console.WriteLine("Enter Your Name");
- string userStringInput = Console.ReadLine();
- string stringResult = Class1.FirstCharToUpper(userStringInput);
- Console.WriteLine(stringResult);
Here, Class1 is the Class Library Class and the FirstCharToUpper is our Extension Method.
Now, see the complete code in our class.
- Console.WriteLine("Enter Any Integer Value" + System.Environment.NewLine);
- int userInput = Convert.ToInt32(Console.ReadLine());
- bool result = userInput.isGreaterThan5();
- Console.WriteLine("The result is " + result);
-
- Console.WriteLine("Enter Your Name");
- string userStringInput = Console.ReadLine();
- string stringResult = Class1.FirstCharToUpper(userStringInput);
- Console.WriteLine(stringResult);
Result
Now, you can see both the results by using two extension methods.
Benefits of extension methods