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()
}
2
Answers
You have to reference the function using the type name. However, a file named
page.cs
likely had a class namedPage
, 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.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 namedpage.cs
and it looks like this in part:(Note that I’ve simplified your initialization of the list – my code is equivalent to yours)
The code I show compiles. Assuming that
MyFunction
andPage_Load
are in the same class, then you can directly callMyFunction
fromPage_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 (sayOtherClass
). ThenPage_Load
could call it in the way @joelcoehoorn describes: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, ifMyFunction
wanted to callPage_Load
, it would need to do something like this: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.