Reputation: 5
The function below is found in a class called page.cs
public static List<string> MyFunction()
{
var retList = new List<string>();
retList.Add("xzy");
retList.Add("abc");
return retList;
}
On page load how to call the function and check if the list contains xzy and abc?
protected void Page_Load(object sender, EventArgs e)
{
//call MyFunction()
}
Upvotes: 0
Views: 1787
Reputation: 7111
You don't really show enough code for us to see your problem. As I read it, you have a class Page
in a file named page.cs
and it looks like this in part:
public class Page {
public static List<string> MyFunction()
{
var retList = new List<string>
{
"xyz",
"abc",
};
return retList;
}
protected void Page_Load(object sender, EventArgs e)
{
var list = MyFunction();
}
}
(Note that I've simplified your initialization of the list - my code is equivalent to yours)
The code I show compiles. Assuming that MyFunction
and Page_Load
are in the same class, then you can directly call MyFunction
from Page_Load
(static functions can be called from instance function (within the same class)).
If they are not in the same class, let's say that MyFunction
was a static function in another class (say OtherClass
). Then Page_Load
could call it in the way @joelcoehoorn describes:
OtherClass.MyFunction();
The reverse is not true. A static function cannot directly call an instance function (one without the static
keyword) in the same class. You'll get an error complaining that you need an instance. For example, if MyFunction
wanted to call Page_Load
, it would need to do something like this:
var page = new Page();
//possibly do something with page
page.PageLoad(new object(), EventArgs.Empty);
//possibly do more stuff with page
If this doesn't answer your question, you need to add more to your question. In particular:
Also note that I don't believe you should be getting Non-invocable member 'page' cannot be used like a method.
if you did what @joelcoehoorn describes.
Upvotes: 2
Reputation: 416131
You have to reference the function using the type name. However, a file named page.cs
likely had a class named Page
, which will conflict with the base ASP.Net Page class. Therefore you must either fully-qualify the name (MyNamespace.Page.MyFunction()
) or change the name of the class.
Upvotes: 1