✔ C# Tutorial
✔ C# Basic
✔ C# Control Statement
✔ C# Function
✔ C# Arrays
✔ C# Object Class
✔ C# Properties
✔ C# Inheritance
✔ C# Polymorphism
✔ C# Abstraction
✔ C# Namespace
✔ C# Exception Handling
✔ C# Collections
✔ C# Misc
Params
params is a keyword in C# that allows a function to accept a variable number of parameters. This means you can pass any number of arguments of a specified type when calling the function.
Let’s explore a simple example:
using System;
class Program
{
// Function using params to accept any number of integers
static void DisplayNumbers(params int[] numbers)
{
foreach (int num in numbers)
{
Console.Write(num + ” “);
}
Console.WriteLine();
}
static void Main()
{
// Call the function with different numbers of arguments
DisplayNumbers(1, 2, 3);
DisplayNumbers(4, 5, 6, 7, 8);
DisplayNumbers(9);
}
}
In this example, the DisplayNumbers function uses params int[] numbers to accept any number of integers. The Main method then calls this function with various numbers of arguments.
The Flexibility of params
params allows you to create functions that adapt to different scenarios. You can pass a single value or an array of values without changing the function signature.
using System;
class Program
{
// Function using params to accept integers and display their sum
static void DisplaySum(params int[] numbers)
{
int sum = 0;
foreach (int num in numbers)
{
sum += num;
}
Console.WriteLine($”Sum: {sum}”);
}
static void Main()
{
// Call the function with different numbers of arguments
DisplaySum(1, 2, 3);
DisplaySum(4, 5, 6, 7, 8);
DisplaySum(9);
}
}
Here, the DisplaySum function uses params int[] numbers to accept any number of integers and calculates their sum.
Combining params with Regular Parameters
You can also combine params with regular parameters in a function. The params parameter must be the last one.
using System;
class Program
{
// Function with a regular parameter and params parameter
static void DisplayInfo(string name, params int[] scores)
{
Console.WriteLine($”Name: {name}”);
foreach (int score in scores)
{
Console.Write(score + ” “);
}
Console.WriteLine();
}
static void Main()
{
// Call the function with a name and different numbers of scores
DisplayInfo(“Alice”, 90, 85, 92);
DisplayInfo(“Bob”, 78, 80);
DisplayInfo(“Charlie”);
}
}
In this example, the DisplayInfo function has a regular parameter name followed by params int[] scores. This allows you to provide a name along with any number of scores.