473,473 Members | 1,848 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

displaying variables using + var + instead of {0}?

I decided to take a class at the local college here and I'm a little
confused about something.

int age = 5;

Console.WriteLine("You are " + age + " years old");

Previously, I had been reading Learning C# and I learned to type
Console.WriteLine('You are {0} years old",age);

The book I'm using now (required for course) is C# by dissection.

At the end of each project it supposidely "disects" the code etc but I don't
think it's doing a very good job because I feel like if I hadn't already
read 6 chapters of Learning C# I'd be pretty confused.

I didn't see it explain what those plus signs were about.

On another code example it's typed

Console.WriteLine(pennies + " pennies");

Why doesn't it have a plus sign before the variable this time?

Thanks
Nov 15 '05 #1
16 1425
The plus sign is simply an indication that you add up different strings.

string str1 = "You are ";
string str2 = age.ToString(); // using an int in Write(Line) causes it to
be converted to a string
string str3 = " years old";

So the first sentence can now be written like
string str4 = str1 + str2 + str3;
Console.WriteLine(str4);

The second line contains only two strings that are added
string str1 = pennies;
string str2 = " pennies";
Console.WriteLine(str1 + str2);

--
Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/
Nov 15 '05 #2
+ add's two strings together.

string szText = "Hello " + "there...";

while the {###} syntax, where ### are numbers from 0 to how many variables
are concerned, takes values that are non-string type, such as int, and
inserts them into your string.

Console.WriteLine ("We are at week {0} of Test number {1}", nWeekNumber,
nTestNumber );

note the following would be invalid:

Console.WriteLine ("We are at week " + nWeekNumber + " of Test number "
+ nTestNumber );

it's invalid because nWeekNumber and nTestNumber cannot be added to a
string, because they are not strings themselves.

hope that helps.
Dan.
"Robert Blackwell" <robbieatwowcentraldotcom> wrote in message
news:%2****************@tk2msftngp13.phx.gbl...
I decided to take a class at the local college here and I'm a little
confused about something.

int age = 5;

Console.WriteLine("You are " + age + " years old");

Previously, I had been reading Learning C# and I learned to type
Console.WriteLine('You are {0} years old",age);

The book I'm using now (required for course) is C# by dissection.

At the end of each project it supposidely "disects" the code etc but I don't
think it's doing a very good job because I feel like if I hadn't already
read 6 chapters of Learning C# I'd be pretty confused.

I didn't see it explain what those plus signs were about.

On another code example it's typed

Console.WriteLine(pennies + " pennies");

Why doesn't it have a plus sign before the variable this time?

Thanks

Nov 15 '05 #3
"Morten Wennevik" <mo************@hotmail.com> wrote in message
news:oprvdn7zo1ge0n9a@localhost...
The plus sign is simply an indication that you add up different strings.


And by adding, he means + returns a new string that represents the
concatenation of two strings.

--
Mike Mayer
http://www.mag37.com/csharp/
mi**@mag37.com
Nov 15 '05 #4
>
Console.WriteLine ("We are at week " + nWeekNumber + " of Test number "
+ nTestNumber );


Actually, this would compile just fine, because WriteLine accepts numbers
as parameters.
--
Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/
Nov 15 '05 #5
"Morten Wennevik" <mo************@hotmail.com> wrote in message
news:oprvdrdey0ge0n9a@localhost...

Console.WriteLine ("We are at week " + nWeekNumber + " of Test number "
+ nTestNumber );


Actually, this would compile just fine, because WriteLine accepts numbers
as parameters.


You are correct that Console.WriteLine takes numbers as parameters (it has
about 18 overloads if I counted correctly). Howver, that is not the reason
that the above compiles. You would be calling the Console.WriteLine(string)
since the result of adding strings to numbers is a longer string.

"We are at week" + nWeekNumber
calls an overloaded + operator that takes a string on the left side, an int
on the right side, and returns a string. Then call + with two strings
(result of first + and the string " of Test number "). Then call + of a
string and a number. The end result is one string, that is passed to
Console.Writeline

--
Mike Mayer
http://www.mag37.com/csharp/
mi**@mag37.com

Nov 15 '05 #6
I believe that when you use the + operator in java, it returns a
StringWriter object, which allows a statement like:

String a = "h" + "e" + "l" + "l" + "o";

to execute just as quickly as if we created a StringWriter and kept
appending letters to it. I was hoping that this was the case in C#, so I
ran the following test. Now, it could be that I just don't understand
reflection well enough in c# yet, or that the + operator is somehow
optimized, so i'd really appreciate some feedback. as of now, it seems
that using the "{###}" notation is more optimized because each string is
only copied once.

public static void Main()
{
string a = "Hello ";
string b = "World!";
Console.WriteLine((a + b).GetType());
}

outputs: System.String

cheers,
ben

Morten Wennevik wrote:
The plus sign is simply an indication that you add up different strings.

string str1 = "You are ";
string str2 = age.ToString(); // using an int in Write(Line) causes it
to be converted to a string
string str3 = " years old";

So the first sentence can now be written like
string str4 = str1 + str2 + str3;
Console.WriteLine(str4);

The second line contains only two strings that are added
string str1 = pennies;
string str2 = " pennies";
Console.WriteLine(str1 + str2);


Nov 15 '05 #7
Robert,
As the others have stated the + is the string concatenation operator, under
the covers C# is calling String.Concat.
Console.WriteLine("You are " + age + " years old");
under the covers becomes:
Console.WriteLine(String.Concat("You are ", age, " years old"));

Normally I prefer: Console.WriteLine('You are {0} years old",age);
As its easier to internationalize, you can replace the "You are {0} years
old" (the format) with a string in a different language (German for
example), because age is a placeholder, the position of age within the
format can move and the Console.WriteLine will still succeed. When
internationalizing you would read the format from a Resource file (.resx or
..resources) using a System.Resources.ResourceManager.

Hope this helps
Jay

"Robert Blackwell" <robbieatwowcentraldotcom> wrote in message
news:%2****************@tk2msftngp13.phx.gbl... I decided to take a class at the local college here and I'm a little
confused about something.

int age = 5;

Console.WriteLine("You are " + age + " years old");

Previously, I had been reading Learning C# and I learned to type
Console.WriteLine('You are {0} years old",age);

The book I'm using now (required for course) is C# by dissection.

At the end of each project it supposidely "disects" the code etc but I don't think it's doing a very good job because I feel like if I hadn't already
read 6 chapters of Learning C# I'd be pretty confused.

I didn't see it explain what those plus signs were about.

On another code example it's typed

Console.WriteLine(pennies + " pennies");

Why doesn't it have a plus sign before the variable this time?

Thanks

Nov 15 '05 #8
Ben T. <be*@jbmsystems.com> wrote:
I believe that when you use the + operator in java, it returns a
StringWriter object, which allows a statement like:

String a = "h" + "e" + "l" + "l" + "o";

to execute just as quickly as if we created a StringWriter and kept
appending letters to it.


In fact it executes significantly quicker in both Java and C#, because
both recognise that everything in the above is a constant. The above is
exactly equivalent to:

String a = "hello";

See Jay's reply for other stuff.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #9
This makes better sense after you explained it since I'm slightly familiar
with PHP and it uses a . instead of a +

echo "Welcome ".$currentUser."!";

so, depending where the variable is being added, before preiod goes after,
between, on both sides, and after period goes before.
Okay, so if I'm understanding you guys correctly {3} is the old way

and + is the new way?

And I probably shouldn't use {0} anymore? or does it depend...

because I thought I remember that if you type something like this
Console.WriteLine("The current road conditions are {0}", (int) icey);

and that would display icey intead of the variable assigned to icey?

I'm not possitive if I typed that correctly, I'd have to go back to my other
book to make sure.
Nov 15 '05 #10
>>and that would display icey intead of the variable assigned to icey?

I meant it would display icey instead of the value assigned to icey
Nov 15 '05 #11
in C#, does it matter if there is a space between the + and the variable?
there's not space between the period in PHP.

or is that just a programmers style preference?
Nov 15 '05 #12
Robert Blackwell <Ro****@dontwowcentralspam.com> wrote:
in C#, does it matter if there is a space between the + and the variable?
No. Whitespace between tokens is mostly irrelevant.
or is that just a programmers style preference?


Yes.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #13
Robert,
Okay, so if I'm understanding you guys correctly {3} is the old way
and + is the new way? No. Consider:

int temp = 100;
int wind = 10;
int rainfall = 0;

string format1 = "Temperature: {0} Wind: {1} Rainfall: {2}";
string format2 = "Wind: {1} Rainfall: {2} Temperature: {0}";
string format3 = "Rainfall: {2} Wind: {1} Temperature: {0} ";

Console.WriteLine(format1, temp, wind, rainfall);
Console.WriteLine(format2, temp, wind, rainfall);
Console.WriteLine(format3, temp, wind, rainfall);

Notice that I use one of three format strings, but the other parameters are
given in a fixed order. Notice that in each format string that I have the
same placeholders {0}, {1}, {2}, but they show up in a different sequence.
If you run the above your output would be:

Temperature: 100 Wind: 10 Rainfall: 0
Wind: 10 Rainfall: 0 Temperature: 100
Rainfall: 0 Wind: 10 Temperature: 100

Now I used English on all three, however consider what happens when format1
is English, format2 = French, format3 = German. & the format string itself
is read from a Resource file which are organized by language.
And I probably shouldn't use {0} anymore? or does it depend... No you should use {0}! especially if you want to internationalize your app.
because I thought I remember that if you type something like this
Console.WriteLine("The current road conditions are {0}", (int) icey);
int icey = 100;
Console.WriteLine("The current road conditions are {0}", (int) icey);

Prints: "The current road conditions are 100"

Hope this helps
Jay

"Robert Blackwell" <Ro****@dontwowcentralspam.com> wrote in message
news:%2****************@TK2MSFTNGP10.phx.gbl... This makes better sense after you explained it since I'm slightly familiar
with PHP and it uses a . instead of a +

echo "Welcome ".$currentUser."!";

so, depending where the variable is being added, before preiod goes after,
between, on both sides, and after period goes before.
Okay, so if I'm understanding you guys correctly {3} is the old way

and + is the new way?

And I probably shouldn't use {0} anymore? or does it depend...

because I thought I remember that if you type something like this
Console.WriteLine("The current road conditions are {0}", (int) icey);

and that would display icey intead of the variable assigned to icey?

I'm not possitive if I typed that correctly, I'd have to go back to my other book to make sure.

Nov 15 '05 #14
Yeah, I think I got it now...was just taken by surprise since it was new and
all.

Thanks guys.
Nov 15 '05 #15
Robert,
The FormatMessage Win32 API works in a similar way, as far as I know its
been around 'for ever'. Only it uses %0, %1, %2 for the place holders.

MFC has a similar function (more than likely uses the above function).

When I worked on As/400s it used &1, &2, &3 for the place holders.

So I'm used to they syntax.

Jay
"Robert Blackwell" <robbieatwowcentraldotcom> wrote in message
news:Ol**************@TK2MSFTNGP11.phx.gbl...
Yeah, I think I got it now...was just taken by surprise since it was new and all.

Thanks guys.

Nov 15 '05 #16
and printf has been around forever and then some...

--
Mike Mayer
http://www.mag37.com/csharp/
mi**@mag37.com
"Jay B. Harlow [MVP - Outlook]" <Ja********@email.msn.com> wrote in message
news:ue**************@TK2MSFTNGP10.phx.gbl...
Robert,
The FormatMessage Win32 API works in a similar way, as far as I know its
been around 'for ever'. Only it uses %0, %1, %2 for the place holders.

MFC has a similar function (more than likely uses the above function).

When I worked on As/400s it used &1, &2, &3 for the place holders.

So I'm used to they syntax.

Jay
"Robert Blackwell" <robbieatwowcentraldotcom> wrote in message
news:Ol**************@TK2MSFTNGP11.phx.gbl...
Yeah, I think I got it now...was just taken by surprise since it was new

and
all.

Thanks guys.


Nov 15 '05 #17

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Dariusz | last post by:
I have constructed a PHP generated HTML layout, which on POSTing the menu option the user selects, calls the same PHP code / page which generates the HTML page and GET's the correct SHTML page into...
14
by: Rahul Chatterjee | last post by:
Hello All I have an asp page in which I am performing the following 1. Querying a database view 2. Returning rows in to a recordset. 3. Looping thru the recordset and printing the data 4....
3
by: Jeanne | last post by:
I am working on a cgi script that is suppose to pop-up a javascript box from the following perl variables:$TodayDate, $LinkCity, $LinkState. I recently encountered a problem with the $LinkCity...
0
by: Wynter | last post by:
RE: from Displaying a Document using the ASPNET user account to the Client Browser discussion (3/2/2004 Buddy Thanks for helping me on getting the document to display. But now I am left with a...
0
by: Fronky | last post by:
Hope someone can help. I am still learning, so no laughing please. I am displaying records from a database using Response.Write(""); instead of the usual datagrid method. I am doing it this way...
5
by: Imran Aziz | last post by:
Hello all, I am populating the contents of a repeater control using a database query. In the repeater control I have a link , which I want to display or not based on the current logged in user....
1
weaknessforcats
by: weaknessforcats | last post by:
C++: The Case Against Global Variables Summary This article explores the negative ramifications of using global variables. The use of global variables is such a problem that C++ architects have...
1
by: johnVarma | last post by:
Hi All, Iam facing a problem with bar chart using coldFusion. if there is only one <cfchartseries> tag then the seriesLabel attribute is not displaying instead of that the items of the...
7
by: RichB | last post by:
I am trying to get to grips with the asp.net ajaxcontrol toolkit, and am trying to add a tabbed control to the page. I have no problems within the aspx file, and can dynamically manipulate a...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.