csharp / intermediate
Snippet
Streamlining Method Invocations with Params Collections
C# 12 expanded the 'params' keyword to support any collection type, not just arrays. This allows methods to accept a comma-separated list of arguments or an existing collection (like List or IEnumerable) interchangeably without manual conversion, improving API flexibility.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
public void ProcessLogs(params IEnumerable<string> messages){foreach (var message in messages){Console.WriteLine($"[LOG]: {message}");}}// UsageProcessLogs("Started", "Processing", "Completed");List<string> list = ["Error 1", "Error 2"];ProcessLogs(list);
Breakdown
1
params IEnumerable<string> messages
Allows the method to accept multiple individual strings or a single IEnumerable object.
2
ProcessLogs("Started", "Processing", "Completed");
The compiler automatically packages these individual arguments into the specified collection type.