Click here to Skip to main content
15,903,201 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I basically started from C++ now in C#,I find formatting confusing.

C#
Console.WriteLine("Number of command line parameters = {0}",
           args.Length);


In above code {0} has been used,this prints out the length of command line args array.
But this work differenetly with {1},see following code.

C#
for (int i = 0; i < args.Length; i++)
        {
            Console.WriteLine("Arg[{0}] = [{1}]", i, args[i]);
        }

output of above code is:

Number of command line parameters = 5
Arg[0] = [abc]
Arg[1] = [def]
Arg[2] = [ghi]
Arg[3] = [klm]
Arg[4] = [nop]


What I want to know is how {0} prints indexes but {1} prints values stored in relevent indexes.
Posted
Updated 11-Dec-13 19:39pm
v3

Because the number inside the { and } within the format string is the index to the following parameters:
Console.WriteLine("{0}:{1}:{2}", a, b, c);
                    ^   ^   ^
                    |   |    -- parameter 2: 'c'
                    |    ------ parameter 1: 'b'
                     ---------- parameter 0: 'a'
It's a way of tieing parameters to positions within the resulting string - they don't have to be in numerical order, or even different!
Console.WriteLine("{1}:{0}:{2}", a, b, c);
Console.WriteLine("{0}:{1}:{0}", a, b)
;
 
Share this answer
 
Comments
Karthik_Mahalingam 12-Dec-13 3:34am    
simple and neat
thatraja 12-Dec-13 4:47am    
5!Done everything nice but your left the last semicolon alone.
Question : What I want to know is how {0} prints indexes but {1} prints values stored in relevent indexes.?

Answer: Because index o refers to loop control variable i, so it aways print loop count like 0,1,2,3,4..etc.,

index 1 refers to the args[i] means -> args[0],args[1],args[2] etc., as args[i] contains command line argument value ,so it prints abc , def ...etc.,
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900