We show how to define public methods. We then call those methods from outside the class. Public is an accessibility modifier. It is not the default, which is private.
using System;
public class Example
{
static int _fieldStatic = 1;
// Private static field
int _fieldInstance = 2;
// Private instance field
public static void DoStatic()
{
// Public static method body.
Console.WriteLine(
"DoAll called");
}
public static int SelectStatic()
{
// Public static method body with return value.
return _fieldStatic * 2;
}
public void DoInstance()
{
// Public instance method body.
Console.WriteLine(
"SelectAll called");
}
public int SelectInstance()
{
// Public instance method body with return value.
return _fieldInstance * 2;
}
}
class Program
{
static void Main()
{
// First run the public static methods on the type.
Example.DoStatic();
Console.WriteLine(Example.SelectStatic());
// Instantiate the type as an instance.
// ... Then invoke the public instance methods.
Example example = new Example();
example.DoInstance();
Console.WriteLine(example.SelectInstance());
}
}
DoAll called
2
SelectAll called
4