Yogi_Bear
Yogi_Bear

Reputation: 594

compiler asked me to make this function static

I dont know why, but the compiler of visual studio asked me to make this function static.

I have many lists of string

List<string> universe = new List<string>();
List<string> foo1 = new List<string>();
List<string> foo2 = new List<string>();
List<string> foo3 = new List<string>();
.
.
.
List<string> fooN = new List<string>();

some of the lists may be empty and other have data, I would like to intersect between those who have data so I made this function:

public List<string> IntersectIgnoreEmpty(this List<string> list, List<string> other)
{
    if (other.Any())
        return list.Intersect(other).ToList();
    return list;
}

and it gave me error until I made it static. I dont know why.

Upvotes: 0

Views: 82

Answers (1)

Maarten
Maarten

Reputation: 22955

You are defining an extension method, since you have added the this keyword to the first parameter.

Extension methods need to be defined as a static method in a static class.

Extension methods are defined as static methods but are called by using instance method syntax. Their first parameter specifies which type the method operates on, and the parameter is preceded by the this modifier. Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive.

If you want to define 'normal' method, remove the this keyword, and it will an instance method on your class.

Upvotes: 6

Related Questions