I have a function in a utility class
namespace GUI.code
{
public class Utility
{
public string GetFileName(string grpID)
{
string filenameUNC = "\\\\" + "localhost" + "\\AgentShare\\";
string realPath = GetPath(filenameUNC);
return realPath;
}
}
}
now i call this function from another page in the project like this:
new utility.GetCSFileName(ID);
why do i need to add new, why cant i call it like
GetCSFileName(ID);
when i have
using GUI.code;
on top
if i remove new i get this error
Error 1 An object reference is required for the non-static field, method, or property 'copiunGUI.code.GUIUtility.GetCSFileName(string)
any suggestions
You can call
Utility.GetFileName()
if you change the declaration topublic static string GetFileName(string grpID)
static
means that the member is shared among all instances of theUtility
class. Remember, c# is an object-oriented language. Non-static members are called instance members, and must be called on a distinct instance of the class. Each time you callnew Utility()
, you are creating such an instance, and this is distinct from every other.This is useful when each instance of a class needs to maintain information (state) internally. If, however, a particular member does not use state data -- it accepts parameters, does work, and optionally returns a result -- it can be declared static. Then you call it not from the instance variable but from the class name itself (in this case
Utility.GetFileName()
.When all of the members of a class are
static
, you can addstatic
to the class declaration itself. At that point, you would never be able to callnew Utility()
, which might be what you want in this case.