What are method parameters in C#?
Answer
Using parameters a method caller can pass values to a method. Method parameters are like boxes that contain values. These parameters have predefined data types and define what values can be passed into the method.
Imagine you want to get your suit cleaned and your shoes polished. There are multiple companies in the city that can do the cleaning services for you. So you select one company that can do this for you, but you need to pass the suit and shoes to this company first.
So you put your suit to one box and your shoes to another box and you will bring or send these boxes to the company and tell it to clean the suit and polish the shoes. The company will take the boxes from you and it will do what you asked it to do with the conents of the boxes.
But it past it was happening that people were sending pets in boxes to the company and the company than didn't know how to handle such boxes. So someone clever said: "Hey, let's accept only boxes that contain suits and shoes. Let's check the contents before we accept any box and if it's not what we expect, then we can reject the order." The rule was put in place and in worked.
Now if we convert this to the C# world:
- There are multiple companies that can provide the same cleaning service. We know that each such company can clean suits and polish shoes.
In C#, this could be represented by class CleaningCompany. The class defines the services the company provides. Such class could contain a method CleanSuitAndPolishShoes() that contains the cleaning and polishing service logic.
The class definition could look like this:
We said that there are multiple companies in the city that provide the same type of service. The companies are of type CleaningComapny.
You decided you will select one company and use its services. In C#, the company is an instance of the CleaningCompany class. We know that each such company has CleanSuitAndPolishShoes() method.
It could look like this.
In C#, we will modify the method CleanSuiAndPolishShoes() like this:
Related C# job interview questions
What does the method signature consist of in C#?
C# JuniorWhat does the method consist of in C#?
C# JuniorIn C#, why can you declare a variable using code 'int x;' but you can't declare a variable using code 'var x;'?
C# JuniorWhat is a breakpoint in C# good for?
C# JuniorHow many classes should be in one .cs file and why?
C# Junior