user2117804
user2117804

Reputation: 1

C#,can Extension methods be added to user defined classes in C#(not base classes)

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

Answers (3)

Manish Basantani
Manish Basantani

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

Oded
Oded

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

ChrisF
ChrisF

Reputation: 137198

Yes you can add an extension method.

public static class MyExtensions
{
    public static bool checkifRollnoIs1(this Student student)
    {
        return student.getrollno() == 1;
    }
}

Source

Though if you have access to the source, why do you need an extension method?

Upvotes: 1

Related Questions