In C#, all functionality is encapsulated within classes. Methods, which define behaviors, must be declared inside a class and cannot exist independently in the global scope. A typical structure begins with a namespace, followed by a class containing methods, and finally a Main method to initiate execution.
Consider a simple calculator that computes geometric areas and volumes:
namespace GeometryCalculator
{
internal class Program
{
static void Main(string[] args)
{
var calc = new Calculator();
Console.WriteLine(calc.CalculateCircleArea(5.0));
}
}
class Calculator
{
public double CalculateCircleArea(double radius)
{
return Math.PI * radius * radius;
}
public double CalculateCylinderVolume(double radius, double height)
{
return CalculateCircleArea(radius) * height;
}
public double CalculateConeVolume(double radius, double height)
{
return CalculateCircleArea(radius) * height / 3.0;
}
}
}
This structure promotes reusability and maintainability. Instead of hardcoding values like 3.14159, using Math.PI ensures precision and avoids errors during future modifications. If multiple constants were scattered throughout the codebase, changing them would require extensive search-and-replace operations, increasing the risk of icnonsistencies.
Methods can be declared as static, allowing them to be invoked without instantiating the class:
namespace GeometryCalculator
{
internal class Program
{
static void Main(string[] args)
{
double result = Calculator.CalculateConeVolume(3.0, 4.0);
Console.WriteLine(result);
}
}
class Calculator
{
public static double CalculateCircleArea(double radius)
{
return Math.PI * radius * radius;
}
public static double CalculateCylinderVolume(double radius, double height)
{
return CalculateCircleArea(radius) * height;
}
public static double CalculateConeVolume(double radius, double height)
{
return CalculateCircleArea(radius) * height / 3.0;
}
}
}
When a method is marked static, it belongs to the class itself, not to any instance. Therefore, you must call it using the class name: Calculator.CalculateConeVolume(...). Attempting to invoke it via an instance like calc.CalculateConeVolume(...) will result in a compile-time error.
C# follows naming conventions to improve code clarity. Method names use PascalCase, where each word starts with a capitol letter (e.g., CalculateCircleArea). This contrasts with camelCase, typically used for local variables and parameters (e.g., radius, height).
When declaring a method, you define its signature including parameter types and names: CalculateConeVolume(double radius, double height). When invoking it, you pass actual values — known as arguments — to match the declared parameters. For example:
- Declaration:
public static double CalculateConeVolume(double radius, double height) - Call:
CalculateConeVolume(3.0, 4.0)
Here, 3.0 and 4.0 are arguments that are asigned to the parameters radius and height during execution.