Junior — Middle
What are the main differences between a method and a function in programming?
sobes.tech AI
Answer from AI
In programming, a function is an independent block of code that performs a specific task and can accept input parameters and return a result. A method is a function that is defined within a class and is associated with an object of that class (or with the class itself if the method is static).
Main differences:
- Call context: a method is called on an object or class, while a function is usually standalone.
- Access to data: a method can work with the internal fields and properties of the class, a function cannot.
- Syntax: in C#, a method is declared inside a class, while a function outside a class (e.g., a local function or static method).
Example of a method in C#:
class Person {
public string Name;
public void SayHello() {
Console.WriteLine($"Hello, my name is {Name}");
}
}
Here, SayHello is a method associated with the Person object.