Yogi_Bear Yogi_Bear - 27 days ago 5
C# Question

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.

Answer

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.

Comments