What are Methods in C-sharp programming language, what is the use of it and how to use methods using parameters? Write a summary of at least 300 words with at least two different examples of C-sharp programs. Make sure to use your own wording. No copy paste from the internet or textbook is allowed. Include at least one reference.
Answer:
Definition:
Method in C-sharp programming language is a unique and separate block of code which consists of a sequence of lines or statements performing specific tasks which are declared inside a class of a C-sharp program. Methods are useful in C-sharp programming language as they highly improve code reusability by making code duplication minimal and also used to perform certain actions. C-sharp programming language has several time of methods which include:
Virtual methods. - It’s a method that is mostly implemented at the class base and can be overridden in the derived class
Extension method- Is a function in C-sharp that allows one to add other new methods in an existing class without changing the source code of the original type.
Pure virtual method. - A member function of a base class which is declared at the base class and defined in derived class.
Instance method. It’s a function that operates on that instance and its data.
Abstract method. - Method that can only be made in Abstract class
Static method – a method that stores only one copy of the method at the type level and not the object level.
In C-sharp programming language a parameter by value is passed by default but parameter by reference can also be passed with the use of a keyword “ref”
Sample C-sharp code on how to pass parameters and return using method:-by value
static void Main(string[] args)// main fuction
{
Console.WriteLine("Enter two digits");
int toPassa = Convert.ToInt32(Console.ReadLine());
int toPassb = Convert.ToInt32(Console.ReadLine());
int result = sumoftwonumbers(toPassa, toPassb);
Console.WriteLine (" The sum of " + toPassa + " and " + toPassb + " is " +result);
Console.Read();
}
static int sumoftwonumbers(int a, int b)// fuction method with parameters passed
{
int sum = a + b;
return sum;
}
Sample C-sharp code to pass a method as parameters:
public class A
{
public int method1(string input);
{
if (input=="go freelancing")
{
return 1;
}else{
return 0 ;
}
public void runmethod(Func method);
{
int i = Method(" go freelancing");
Console.Writeline(i)
Console.Readkey();
}
public void test()
{
runmethod(method1)
}
}
Reference(s):
Microsoft Corporation, Methods in (C#) , Accessed 16 July 2021,
< https://docs.microsoft.com/en-us/dotnet/csharp/methods>