38
loading...
This website collects cookies to deliver better user experience
methods
.<access modifier> <instance or static> <return type> <method name>(<paramenters>)
{
}
public
access modifier.void
keyword.WriteToConsole
.string message
public void WriteToConsole(string message)
{
// code
}
Add
, it recieves to paramenters value1
and value2
, both of type int
, and returns the sum of both paramenters, indicated by the return
keyword.public int Add(int value1, int value2)
{
return value1 + value2;
}
Access Modifier
defines how the code can access part of your code. They are used not only for methods, but for classes, properties, enums, etc.Modifier | Description |
---|---|
private | The code can only be accessed inside the same class. |
public | The code can be accessed for everyone. |
internal | The code can only be accessed. |
protected | The code can only be accessed inside the same class or classes that inherit from the declaring class. |
// Accessed public inside the project
public internal ...
// Accessed inly by classes that inherit an inside the same project
protected internal
static
keyword, is always an instance method.Instance
method, first, you need to instantiate an object and it works with the instance data.public class Calculator
{
public int Add(int x, int y)
{
return x + y;
}
}
public static Main()
{
Calculator calc = new Calculator();
int result = calc.Add(5,6);
}
public class Calculator
{
public int X {get; set;}
public int Y {get;set;}
public int Add()
{
return X + Y;
}
}
static void Main()
{
Calculator calc1 = new Calculator();
calc1.X = 5;
calc1.Y = 10;
int result1 = calc1.Add();
Calculator calc2 = new Calculator();
calc2.X = 22;
calc2.Y = 20;
int result2 = calc2.Add();
Console.WriteLine(result1); // Prints 15
Console.WriteLine(result2); // Prints 42
}
public class Calculator
{
public static int Add(int x, int y)
{
return x + y;
}
}
public static void Main()
{
// calling a static method.
int result = Calculator.Add(5,6);
}
return
keyword. void
methods does not return a value.public void ExecuteAndDoesNotReturnAValue()
{
// code
{
public string ExecuteAndReturnsAValue()
{
return "This method has a return value";
}
// The method signatures has parameters
// In this case, two paramenters, x and y
public int Add(int x, int y)
{
return x + y;
}
public static Main()
{
Calculator calc = new Calculator();
// When calling the method, we pass **arguments** to its **paramenters**
// in this scenario, we are passing 5 to x and 6 to y
int result = calc.Add(5,6);
}
public class Calculator
{
/// returns the sum of a and b
public int Add(int a, int b)
{
return a + b;
}
// returns the sum of a, b and c
public int Add(int a, int b, int c)
{
return a + b + c;
}
}