Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add methods to base class c#

Is that possible to add methods to Base classes like List? or others? I really need to add method to generic list class if it has MyClass type. like this: List<MyClass>.FindCoolStuff() or List<MyClass>.SetValueByName()

thanks

like image 607
Novikov Avatar asked Mar 24 '26 12:03

Novikov


1 Answers

No, but you can use an extension method.

public static class ListExtensions
{
    public static IEnumerable<T> DoCoolStuff<T>(this List<T> collection)
    {
        // Do cool stuff
    }
}

From MSDN: In your code you invoke the extension method with instance method syntax.

var awesomeList = new List<string>();

var awesomestuff = awesomeList.DoCoolStuff();
like image 102
Dustin Kingen Avatar answered Mar 26 '26 01:03

Dustin Kingen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!