Passing indefinite parameters as Method arguments in C#

One might have a situation where he or she needs to pass a number of variables as arguments at runtime. When we are sure of the parameters required, we can declare them in method signature, like

         public static void PrintMessage(string message, int times)
        {
            for (int i = 0; i < times; i++)
                Console.WriteLine(message);
        }

In the above example we know that we need a message as string and an int (times) which would be used to display the message a number of times. What if we do not know how many variables of some type or different types are required at compile time, like print a number of messages, together or message or names . Here is params keyword which will gracefully tackle this situation. If we need list of argument of particular type, like string

         public static void PringtMessages(params string[] stringsList)
        {
            foreach (string s in stringsList) { }   
            // your logic here
        }

        // this is how to call
        string[] messages = new string[] { "Message1", "Message2" };
        PringtMessages(messages);

This is how, if we a need to pass different type of objects as indefinite number of arguments

        public static void PrintMessageWithID(params object[] list)
        {
            foreach (string s in list) { } 
            // your logic here
        }
        object[] messageAndId = new object[] { "Message1", 1,  "Message2", 2 };
        PrintMessageWithID(messageAndId);
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s