Can you create a function in C# which can accept varying number of arguments?
Can you create a function in C# which can accept varying number of arguments?
Yes, you can create a function in C# that can accept a varying number of arguments using the params keyword. Here's an example:
public static int Sum(params int[] numbers)
{
int total = 0;
foreach (int number in numbers)
{
total += number;
}
return total;
}
In this example, the Sum function uses the params keyword to accept an array of integers as arguments. The function can be called with any number of integer arguments, and they will be treated as an array inside the function.
Here's how you can call the Sum function with varying arguments:
int result1 = Sum(1, 2, 3); // result1 = 6
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.