Functions and methods are both blocks of code that perform a specific task. However, there are some differences between the two in C#.
Functions:
– Functions are blocks of code that can be called and return a value.
– Functions are typically defined outside of a class, although they can also be defined inside a class.
– The return type of a function is specified in the function signature.
– Functions can have parameters that are passed in when the function is called.
– Example:
“`csharp
public int Add(int a, int b)
{
return a + b;
}
“`
Methods:
– Methods are blocks of code that perform a specific task, but do not return a value.
– Methods are defined within a class.
– Methods can have access modifiers like public or private.
– Methods can have parameters that are passed in when the method is called.
– Example:
“`csharp
public void PrintHello(string name)
{
Console.WriteLine(“Hello, ” + name + “!”);
}
“`
In summary, functions are blocks of code that can be called and return a value, while methods are blocks of code that perform a task but do not return a value.