In C#, a method is a block of code that performs a specific task, and parameters and return types are crucial components of method signatures.
Parameters:
1. Defining a Method with Parameters:
In C#, you can define a method with parameters to receive input values.
class Program{// Method with parametersstatic void PrintMessage(string message){Console.WriteLine(message);}static void Main(){// Calling the method with an argumentPrintMessage("Hello, C#!");}}
In this example, PrintMessage
is a method that takes a string
parameter named message
.
2. Multiple Parameters:
You can have multiple parameters in a method.
class Program{// Method with multiple parametersstatic void PrintDetails(string name, int age){Console.WriteLine($"Name: {name}, Age: {age}");}static void Main(){// Calling the method with multiple argumentsPrintDetails("John Doe", 25);}}
3. Default Values:
You can provide default values for parameters.
class Program{// Method with a default parameter valuestatic void PrintGreeting(string name, string greeting = "Hello"){Console.WriteLine($"{greeting}, {name}!");}static void Main(){// Calling the method with and without providing the second argumentPrintGreeting("Alice");PrintGreeting("Bob", "Hi");}}
Return Types:
1. Methods with Return Types:
A method can return a value. Specify the return type in the method signature.
class Program{// Method with a return typestatic int Add(int a, int b){return a + b;}static void Main(){// Calling the method and storing the resultint sum = Add(3, 5);Console.WriteLine($"Sum: {sum}");}}
2. Void Return Type:
If a method doesn't return any value, use the void
return type.
class Program{// Method with void return typestatic void DisplayMessage(string message){Console.WriteLine(message);}static void Main(){// Calling the method with no need to store the resultDisplayMessage("Welcome to C#!");}}
3. Returning Objects:
A method can also return objects of custom classes or built-in types.
class Program{// Method returning an objectstatic Person CreatePerson(string name, int age){return new Person { Name = name, Age = age };}static void Main(){// Calling the method and working with the returned objectPerson person = CreatePerson("Jane Doe", 30);Console.WriteLine($"Person: {person.Name}, Age: {person.Age}");}}// Custom class for demonstrationclass Person{public string Name { get; set; }public int Age { get; set; }}
Now you have a basic understanding of how to work with parameters and return types in C#. Feel free to experiment and build upon these concepts in your own projects!