Methods - Learn Object-Oriented Programming in C#
Methods - Learn Object-Oriented Programming in C#
Object-oriented Programming
in C#
10% completed
Search Module
Introduction to Object-
Oriented Programming
in C#
Access Modifiers
Fields
Methods
These methods can either alter the data stored in the fields or use their existing
values to perform a certain computation. All the useful methods should be public,
although, some methods which do not need to be accessed from the outside could
be kept private.
1 class VendingMachine {
2
3 // Public method implementation to print print the bought product
4 public void Buy(string product) {
5 Console.WriteLine("You bought: " + product);
6 }
7
8 }
9
10 class Demo {
11
12 public static void Main(string[] args) {
13 var vendingMachine = new VendingMachine();
14 vendingMachine.Buy("Chocolate"); // Calling public method
15 }
16
17 }
Got any feedback? Get in touch with us.
Return Statement
For methods that define a return type, the return statement must be immediately
followed by the return value.
The return type, string, which comes before the method name GetManufacturer,
indicates that this method returns a string.
Got any feedback? Get in touch with us.
Method Overloading
We could redefine a method several times with the same name but with a different
number of arguments and/or types. When the method is called, the appropriate
definition will be selected by the compiler at the compile time.
Let’s see this in action by overloading the product method in the Calculator class:
1 class Calculator {
2
3 public double Product(double x, double y) {
4 return x * y;
5 }
6
7 // Overloading the function to handle three arguments
8 public double Product(double x, double y, double z) {
9 return x * y * z;
10 }
11
12 // Overloading the function to handle int
13 public int Product(int x, int y){
14 return x * y;
15 }
16
17 }
18
19 class Demo {
Got any feedback? Get in touch with us.
20
21 public static void Main(string[] args) {
22 Calculator calculator = new Calculator();
23
24 double x = 10;
25 double y = 20;
26 double z = 5;
27
28 int a = 12;
29 int b = 4;
30
31 Console WriteLine(calculator Product(x y));
In the code above, we see the same method behaving differently when encountering
different number and types of arguments.
Note: Methods that have no arguments and differ only in the return types
cannot be overloaded since the compiler won’t be able to differentiate
between their calls.
In the next lesson, you will get to know about static and non-static methods.