Complete C# Tutorial

Learn Params in C# - Parameter Arrays Examples Made Easy

Introduction 🎯

Ever gone grocery shopping without knowing how many items you’ll buy? 🛒 Sometimes it’s just milk, and other times it’s a whole cart full! Similarly, what if you need to pass a variable number of arguments to a method in C#?

That’s where the params in C# keyword comes in handy! 🙌 It lets you pass zero, one, or many parameters without creating multiple overloaded methods.

Sounds awesome, right? Let’s explore this with fun and relatable examples! 😃

What is Params in C#? 🤔

The params keyword allows you to pass a variable number of arguments to a method. This means you can pass any number of values—even none at all!

It’s super useful when you don’t know how many inputs you’ll need ahead of time.

Why Use Params in C#? 💡

✅ Makes your methods flexible and clean
✅ Avoids writing multiple overloaded methods
✅ Perfect when you don’t know how many arguments you’ll need
✅ Handles zero to many parameters easily

Syntax of Params in C#:

				
					returnType MethodName(params DataType[] parameterName)
{
    // Method body
}
				
			

🔑 Important:

  • params must be the last parameter in the method.
  • You can pass no arguments or multiple arguments.
  • Only one params parameter is allowed per method.

Simple Example: Adding Numbers 🧮

Let’s start with a basic example. Imagine you’re making a calculator that adds numbers. You don’t want to create separate methods for 2, 3, or 10 numbers, right? 😅

Here’s how params in C# can save you!

Code:

				
					using System;

class Program
{
    static void AddNumbers(params int[] numbers)
    {
        int sum = 0;
        foreach (int num in numbers)
        {
            sum += num;
        }
        Console.WriteLine($"Sum: {sum}");
    }

    static void Main()
    {
        AddNumbers(1, 2, 3);      // Passing 3 numbers
        AddNumbers(5, 10);        // Passing 2 numbers
        AddNumbers();             // Passing no numbers
    }
}
				
			

Output

				
					Sum: 6  
Sum: 15  
Sum: 0  
				
			

Explanation:

  • In AddNumbers, we use params int[] numbers.
  • You can pass any number of integers—even none!
  • The method adds all provided numbers.

Super flexible, right? 😎

Real-World Example: Sending Notifications 📩

Imagine you’re building an app that sends notifications. Sometimes you notify one user, and other times, many users.

Let’s see how C# Parameter Arrays examples can make this easy:

Code:

				
					using System;

class Program
{
    static void SendNotification(params string[] users)
    {
        if (users.Length == 0)
        {
            Console.WriteLine("No users to notify.");
            return;
        }

        foreach (var user in users)
        {
            Console.WriteLine($"Notification sent to {user}");
        }
    }

    static void Main()
    {
        SendNotification("Alice");                       // Single user
        SendNotification("Bob", "Charlie", "David");     // Multiple users
        SendNotification();                              // No users
    }
}
				
			

Output:

				
					Notification sent to Alice  
Notification sent to Bob  
Notification sent to Charlie  
Notification sent to David  
No users to notify.  
				
			

Explanation:

  • SendNotification uses params string[] users.
  • You can pass any number of user names.
  • No users? It gracefully handles that too! 🥳

Think about how useful this is for messaging apps or email systems! 📬

More C# Parameter Arrays Examples 🚀

Example 1: Printing Shopping List 🛍️

You never know how many items you’ll buy. Let’s handle that with params:

				
					using System;

class Program
{
    static void PrintShoppingList(params string[] items)
    {
        if (items.Length == 0)
        {
            Console.WriteLine("Shopping list is empty.");
            return;
        }

        Console.WriteLine("Shopping List:");
        foreach (var item in items)
        {
            Console.WriteLine($"- {item}");
        }
    }

    static void Main()
    {
        PrintShoppingList("Milk", "Eggs", "Bread");
        PrintShoppingList("Apples");
        PrintShoppingList();  // No items
    }
}
				
			

Output:

				
					Shopping List:  
- Milk  
- Eggs  
- Bread  

Shopping List:  
- Apples  

Shopping list is empty.  
				
			

See how it adapts to different input sizes? So handy! 🛒

Example 2: Calculating Average Scores 📊

Teachers often enter different numbers of scores. Let’s make it easy for them!

				
					using System;

class Program
{
    static void CalculateAverage(params double[] scores)
    {
        if (scores.Length == 0)
        {
            Console.WriteLine("No scores provided.");
            return;
        }

        double total = 0;
        foreach (double score in scores)
        {
            total += score;
        }

        double average = total / scores.Length;
        Console.WriteLine($"Average Score: {average:F2}");
    }

    static void Main()
    {
        CalculateAverage(85.5, 90.0, 78.5);
        CalculateAverage(100.0);
        CalculateAverage();  // No scores
    }
}
				
			

Output:

				
					Average Score: 84.67  
Average Score: 100.00  
No scores provided.  
				
			

Perfect for grading apps or survey tools! ✅

Example 3: Concatenating Strings ✨

Want to merge different strings into one sentence? Let’s do it!

				
					using System;

class Program
{
    static void Concatenate(params string[] words)
    {
        string sentence = string.Join(" ", words);
        Console.WriteLine($"Sentence: {sentence}");
    }

    static void Main()
    {
        Concatenate("Hello", "world!");
        Concatenate("Coding", "is", "fun!");
        Concatenate();  // No words
    }
}
				
			

Output:

				
					Sentence: Hello world!  
Sentence: Coding is fun!  
Sentence:   
				
			

Super useful for creating dynamic messages! 📝

🏁 Conclusion

Awesome job making it to the end! 🎉 Now you know how to use parameter arrays (params) in C# to pass a variable number of arguments to methods. This is super helpful when you don’t know how many values you’ll need to pass. Instead of creating multiple overloaded methods, you can just use params and keep your code clean and flexible!

Remember how we compared it to ordering pizza with different toppings? 🍕 Whether you have just one topping or a dozen, the params keyword handles it all. Pretty cool, right? 😎 Plus, you’ve seen how this concept can be applied in real-world scenarios like calculating expenses or printing shopping lists.

If you found this lesson helpful, you’re on the right track! Keep practicing and try creating your own methods using params. You’ll be surprised how often this comes in handy.

 

🚀 Next what?

You did it! 🎉 You’ve mastered params in C# and seen how it simplifies code!

But wait—there’s more! 😉

In the next chapter, you’ll learn about Optional & Named Parameters. These gems make your method calls even more flexible! Excited? Stay tuned! 🚀✨

Leave a Comment

Share this Doc

Parameter Arrays (params)

Or copy link