Reputation: 1
I have a user defined class
public class Student
{
int rollno;
public getrollno()
{
return rollno;
}
}
I want to have extension method checkifRollnoIs1()
which will return true or false.
Can I do it & how can I do it?
Upvotes: 0
Views: 452
Reputation: 17509
You can add extension method for "any" object that could be passed to a Static method for some operation.
For compiler, extension method is nothing more than a static method.
If you have a extension method for "CheckIfRollNoIs1", in that case your call,
studentObj.CheckIfRollNoIs1()
gets converted to,
StudentExtensions.CheckIfRollNoIs1(studentObj)
Upvotes: 1
Reputation: 499392
Here is one way to write one:
public static class StudentExtensions
{
public static bool checkifRollnoIs1(this Student s)
{
return s.getrollno() == 1;
}
}
By the way - extension methods are not actually added to a class, they just appear that way (intellisense magic).
Upvotes: 6