Variable argument lists in C#

Share

These would be called varargian functions in C… It turns out they’re possible with C#. Check it out:

    using System;
    using System.Text;
    
    namespace varargs
    {
    	class Class1
    	{
    		[STAThread]
    		static void Main(string[] args)
    		{
    			Console.WriteLine(printf("This %s a %s string", "is", "format"));
    		}
    
    		// The worst printf ever written
    		static string printf(string format, params object[] args)
    		{
    			int idx = 0;
    			bool insideFormatChar = false;
    			StringBuilder result = new StringBuilder();
    
    			for(int i = 0; i < format.Length; i++)
    			{
    				if(insideFormatChar)
    				{
    					if(format[i] == '%') result.Append("%");
    					else result.Append(args[idx++].ToString());
    					insideFormatChar = false;
    				}
    				else if(format[i] == '%') insideFormatChar = true;
    				else
    				{
    					result.Append(format[i]);
    				}
    			}
    
    			return result.ToString();
    		}
    	}
    }
    
Share