C#: Methods & Classes
What you will learn
How to define methods and classes, the anatomy of a method signature, and the use of static.
Class and method structure
public class Greeter {
public static string Greet(string name) {
return $"Hello, {name}!";
}
public static void Main(string[] args) {
Console.WriteLine(Greet("Alice"));
}
}
Method anatomy
- access modifier:
public,private,internal,protected - static: belongs to the class, not an instance
- return type:
voidmeans no return value - method name: PascalCase by convention
- parameters: typed, in parentheses
- body: in
{ }
Properties (C# special feature)
Properties are like smart fields with get/set accessors:
public class Person {
public string Name { get; set; } // auto-property
public int Age { get; private set; } // read-only externally
public DateTime CreatedAt { get; } = DateTime.Now; // getter only
}
String interpolation with $
string name = "Alice";
int age = 25;
Console.WriteLine($"{name} is {age} years old.");
Common mistakes
- Forgetting that
Mainmust bestatic— the CLR calls it before any object is created - Using
string.Formatinstead of$""— interpolation is cleaner and faster - Confusing
publicandprivate— members areprivateby default in C# - Naming methods in camelCase — C# conventions use PascalCase for methods and properties
Quick check below!