473,811 Members | 3,579 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

c# interview question

Hi,

I recently had an interview where I was asked a number of questions on C#.
Unfortunately I didn't get the answers from the test and find that one of
them is still niggling me.

It was something like this:

Consider the following code:

int i = 0;
Console.WriteLi ne("The value is: " + i);
Console.WriteLi ne("The value is: " + i.ToString());

Which would you use to write an integer to the console and why would it give
better performance?

I said I would use: Console.WriteLi ne("The value is: " +
i.ToString());

But I can't think why this should give a performance advantage. I can only
guess that the compiler should be able to realise that a string is required
from the integer for the line not using the ToString() method and generate
the same MSIL.

Can anyone please enlighten me?

Best Regards,

Steve
Mar 12 '07
34 2586
DeveloperX <nn*****@operam ail.comwrote:
I agree it's type safe, but the former passes an int and a string as
object parameters and the latter two strings to string parameters.
Given the choice I'd rather use the most accurate signature available
for what I want to do, in this case concat two strings. Ok, string
concatenation probably isn't the best example as it's really simple
and I do take your point on readability. I personally think I prefer
the ToString version as it's obvious that I want the int's string
representation. Imagine this example:

int i=1;
int j=2;
Console.WriteLi ne("My value is: " + i + j);
Console.WriteLi ne("My value is: " + (i + j));
Console.WriteLi ne(i + j);

Suddenly I get
My value is: 12
My value is: 3
3

So if a developer simply removed the string literal the intention of
the line of code changes.
I would never use the first form - always the second or third. They're
both perfectly readable, IMO, and I think string concatenation is
sufficiently "part of the language" that it's obvious that when I'm
concatenating a string and an int, that I want the string
representation of the int.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Mar 12 '07 #21
On 12 Mar, 17:17, "Mike Schilling" <mscottschill.. .@hotmail.com>
wrote:
"DeveloperX " <nntp...@operam ail.comwrote in message

news:11******** **************@ c51g2000cwc.goo glegroups.com.. .


On 12 Mar, 10:45, "Mike Schilling" <a...@newsgroup .nospamwrote:
"Steve Bugden" <SteveBug...@di scussions.micro soft.comwrote in message
>news:60******* *************** ************@mi crosoft.com...
Hi,
I recently had an interview where I was asked a number of questions on
C#.
Unfortunately I didn't get the answers from the test and find that one
of
them is still niggling me.
It was something like this:
Consider the following code:
int i = 0;
Console.WriteLi ne("The value is: " + i);
Console.WriteLi ne("The value is: " + i.ToString());
Which would you use to write an integer to the console and why would it
give
better performance?
By definition, they mean exactly the same thing, so it doesn't matter
which
one you use. (If it were possible for "i" to be null, the first one
would
be better, since it could never cause a null reference exception, but a
value type can't be null.) The analyses in other posts in the thread
aren't
about the difference between these two statements, they're about what IL
a
particular version of the compiler happens to generate. If these people
expect you to know that off the top of your head, they're idiots.
Likewise,
if these people think that the difference between the two sets of
generated
IL cause any measurable difference in performance, they're idiots.
I said I would use: Console.WriteLi ne("The value is: " +
i.ToString());
But I can't think why this should give a performance advantage. I can
only
guess that the compiler should be able to realise that a string is
required
from the integer for the line not using the ToString() method and
generate
the same MSIL.
Can anyone please enlighten me?
Best Regards,
Steve- Hide quoted text -
- Show quoted text -- Hide quoted text -
- Show quoted text -
Sorry but that just isn't true.
The IL shows perfectly the different behaviours of the two lines. The
first will box into an object, call Concat(object, object) which
internally will call Concat(string, string). The second only calls
Concat(string, string) Any internal compiler optimisations would have
to honour that behaviour.

Why, when they result in identical behavior? C# is a high-level language,
not assembler.

So the IL disassembly shows exactly what the
difference between the two lines of code are and would not be markedly
different regardless of whether you compiled it under VS or say Mono.
The OP wanted to know what the difference was based on his interview
and he got several good answers.
Regarding performance. One is more performant than the other. Running
the above example won't yield a noticable difference in speed, doing
so with a more complex example in a tight loop over millions of
iterations would.

Can you demonstrate that? Seriously, build a test and tell us the results.- Hide quoted text -

- Show quoted text -
I showed the performance back up the thread,
I can try and compile something up under mono, but my assertion is
based on the fact they use ECMA-335 for the CIL and and 334 for C#.
Regardless of whether they've rewritten Concat(object, object) to look
slightly different to Redmond's interpretation, it will have to a) box
the int, b) call ToString on both the string and the now boxed int. c)
return the result.
These are the critical bits.

Mar 12 '07 #22

"DeveloperX " <nn*****@operam ail.comwrote in message
news:11******** *************@3 0g2000cwc.googl egroups.com...
I showed the performance back up the thread,
I can try and compile something up under mono, but my assertion is
based on the fact they use ECMA-335 for the CIL and and 334 for C#.
Regardless of whether they've rewritten Concat(object, object) to look
slightly different to Redmond's interpretation, it will have to a) box
the int, b) call ToString on both the string and the now boxed int. c)
return the result.
These are the critical bits.
Performance is something you measure. If it doesn't result in a measurable
performance different (e.g., if the JIT smooths out the difference), there's
no performance issue.

And that's aside from the fact that even if you can measure it, this sort of
micro-optimization would be about 10,000th on the list of things you should
worry about. It's like skipping lunch to improve your gas mileage.
Mar 12 '07 #23
On Mar 12, 4:39 am, Steve Bugden
<SteveBug...@di scussions.micro soft.comwrote:
Hi,

I recently had an interview where I was asked a number of questions on C#.
Unfortunately I didn't get the answers from the test and find that one of
them is still niggling me.

It was something like this:

Consider the following code:

int i = 0;
Console.WriteLi ne("The value is: " + i);
Console.WriteLi ne("The value is: " + i.ToString());

Which would you use to write an integer to the console and why would it give
better performance?

I said I would use: Console.WriteLi ne("The value is: " +
i.ToString());

But I can't think why this should give a performance advantage. I can only
guess that the compiler should be able to realise that a string is required
from the integer for the line not using the ToString() method and generate
the same MSIL.

Can anyone please enlighten me?

Best Regards,

Steve
Steve,

Console.WriteLi ne accounts for 99% percent of the execution time.
It's so significant, in fact, that when I ran tests I observed no
difference. Even after removing the method call I only observed a 5%
increase in speed by using the ToString() version. This micro
optimization is so insignificant that it's unlikely to ever be
perceptible in the context of an entire application.
The only thing that makes this interview question interesting to me is
that it asks "why?" at the end.

Brian
Mar 12 '07 #24
On 12 Mar, 18:19, "Mike Schilling" <mscottschill.. .@hotmail.com>
wrote:
"DeveloperX " <nntp...@operam ail.comwrote in message

news:11******** *************@3 0g2000cwc.googl egroups.com...
I showed the performance back up the thread,
I can try and compile something up under mono, but my assertion is
based on the fact they use ECMA-335 for the CIL and and 334 for C#.
Regardless of whether they've rewritten Concat(object, object) to look
slightly different to Redmond's interpretation, it will have to a) box
the int, b) call ToString on both the string and the now boxed int. c)
return the result.
These are the critical bits.

Performance is something you measure. If it doesn't result in a measurable
performance different (e.g., if the JIT smooths out the difference), there's
no performance issue.

And that's aside from the fact that even if you can measure it, this sort of
micro-optimization would be about 10,000th on the list of things you should
worry about. It's like skipping lunch to improve your gas mileage.
To be honest Mike, I'm really not that interested. This thread has
gone totally off the rails. Concat is a red herring. You insist on
speaking in specifics while I deal with generalities. I posted the IL
to show that the int is boxed and it will then call Concat again. I
prefer using ToString because to my mind it indicates that I want a
string. In reality I'd probably use something more like the format I
used to output the three tick counts. For the sake of the interview
question I'd take the ToString version for the following reason:

Jon, I take your point regarding readability, I always do. In this
case I disagree to a point. As you say, it should always be implied
that if I + a string and an int I want the int's string
representation, my point was to show if you lose the string the +
reverts to a mathematical operator giving the wrong result (I have
seen this occur in code where a developer has changed how a composite
key was generated). Again, this is all very specific and not what I
originally intended to show.
I'd also argue that it's moot anyway. The majority of the time I'm
using a string builder, or not concatentating and having to use
ToString anyway. For that reason, I can also say I use it out of force
of habit.

Brian, in my example I removed all the WriteLine statements for
exactly that reason. I understand your point, I'm not going to have an
application that just Concats strings and then exits. Again, this is
too specific an example and I was responding to rage filled Mike in
his initial IL bashing. If I'm operating on a huge set of data I'll
take any optimisations I can get. If I can knock five minutes off an
hour long job it's worth it (to me, in my environment). I won't get
that from Concat sure, that's not really the point. This isn't a real
world test, it's a poor interview question that does not represent the
programming challenges we all face every day.

Mar 13 '07 #25
I believe all value types have an inherent ToString method. I don't see why
one of these methods would be any different than the other.

Robin S.
--------------------------------
"glenn" <gl**********@y ahoo.co.ukwrote in message
news:e0******** *******@TK2MSFT NGP04.phx.gbl.. .
I'm wrong, of course it would compile.

Must read documentation before posting, must read documentation before
posting...

"glenn" <gl**********@y ahoo.co.ukwrote in message
news:uZ******** *****@TK2MSFTNG P02.phx.gbl...
>Steve

The code with the ToString() call would be quicker 'cus I don't think
the first would even compile.

Personally, I think it should have been

Console.WriteL ine( "This value is: {0}", i );

In this case ToString would be called anyway, so an explicit call to
ToString() is superfluous.

Glenn

"Steve Bugden" <St*********@di scussions.micro soft.comwrote in message
news:60******* *************** ************@mi crosoft.com...
>>Hi,

I recently had an interview where I was asked a number of questions on
C#.
Unfortunate ly I didn't get the answers from the test and find that one
of
them is still niggling me.

It was something like this:

Consider the following code:

int i = 0;
Console.WriteLi ne("The value is: " + i);
Console.WriteLi ne("The value is: " + i.ToString());

Which would you use to write an integer to the console and why would it
give
better performance?

I said I would use: Console.WriteLi ne("The value is: " +
i.ToString()) ;

But I can't think why this should give a performance advantage. I can
only
guess that the compiler should be able to realise that a string is
required
from the integer for the line not using the ToString() method and
generate
the same MSIL.

Can anyone please enlighten me?

Best Regards,

Steve



Mar 13 '07 #26
DeveloperX <nn*****@operam ail.comwrote:
Jon, I take your point regarding readability, I always do. In this
case I disagree to a point. As you say, it should always be implied
that if I + a string and an int I want the int's string
representation, my point was to show if you lose the string the +
reverts to a mathematical operator giving the wrong result (I have
seen this occur in code where a developer has changed how a composite
key was generated).
I would always bracket things if there was any chance of it being
wrong, so it's not an issue for me, and the ToString() just adds fluff
as far as I'm concerned.
Again, this is all very specific and not what I
originally intended to show.
But it does address your incredulity that anyone would ever use a
non-optimal piece of code.
I'd also argue that it's moot anyway. The majority of the time I'm
using a string builder, or not concatentating and having to use
ToString anyway. For that reason, I can also say I use it out of force
of habit.
You don't have to use ToString() if you're using a StringBuilder - and
if you use StringBuilder where String.Concat would do the same thing,
*that's* less performant (and far less readable).

<snip>

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Mar 13 '07 #27
On 13 Mar, 07:32, Jon Skeet [C# MVP] <s...@pobox.com wrote:
DeveloperX <nntp...@operam ail.comwrote:
Jon, I take your point regarding readability, I always do. In this
case I disagree to a point. As you say, it should always be implied
that if I + a string and an int I want the int's string
representation, my point was to show if you lose the string the +
reverts to a mathematical operator giving the wrong result (I have
seen this occur in code where a developer has changed how a composite
key was generated).

I would always bracket things if there was any chance of it being
wrong, so it's not an issue for me, and the ToString() just adds fluff
as far as I'm concerned.
Again, this is all very specific and not what I
originally intended to show.

But it does address your incredulity that anyone would ever use a
non-optimal piece of code.
I'd also argue that it's moot anyway. The majority of the time I'm
using a string builder, or not concatentating and having to use
ToString anyway. For that reason, I can also say I use it out of force
of habit.

You don't have to use ToString() if you're using a StringBuilder - and
if you use StringBuilder where String.Concat would do the same thing,
*that's* less performant (and far less readable).

<snip>

--
Jon Skeet - <s...@pobox.com >http://www.pobox.com/~skeet Blog:http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Yes, sorry I meant use ToString if I'm doing a direct assignment, but
not with StringBuilder, I should of bracketed my Or :)

A little incredulous, but not really. I'd rather my code was clean and
safe and performant. I've no problem with things like cascading
through a bunch of ctors because you only want to supply one of half a
dozen defaults. It may be faster to call the one that actually does
the work, but clearly asinine to supply all those default values each
time. Just an example.

Oh well as I said, The entire thread went off topic, my original
intention was to show the different operation of the two lines, I
didn't expect to be called an idiot for trying to explain how
something works, so apologies if I came across as overly defensive.
Mar 13 '07 #28
On Mar 13, 8:28 am, "DeveloperX " <nntp...@operam ail.comwrote:
Oh well as I said, The entire thread went off topic, my original
intention was to show the different operation of the two lines, I
didn't expect to be called an idiot for trying to explain how
something works, so apologies if I came across as overly defensive.
I certainly don't think you are an idiot. Afterall, you were
resourceful enough to ILDASM it to explore, understand, and explain
the differences in the two lines. I think most people would agree
that it's more important to demonstrate those skills to memorize the
answers to trick one-liners.

Mar 13 '07 #29
DeveloperX wrote:
time. Just an example.

Oh well as I said, The entire thread went off topic, my original
intention was to show the different operation of the two lines, I
didn't expect to be called an idiot for trying to explain how
something works, so apologies if I came across as overly defensive.
I wasn't calling you an idiot, but the interviewer, for

1. Considering this bit of trivia important, and
2. Expecting the OP to know it off the top of his head.

I disagree with you that there's clearly a performance issue here; there's
no way of telling that without knowing what the JIT output looks like, but I
wouldn't insult you over that.
Mar 13 '07 #30

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

Similar topics

54
17450
by: Spammay Blockay | last post by:
I've been tasked with doing technical interviews at my company, and I have generally ask a range of OO, Java, and "good programming technique" concepts. However, one of my favorite exercises I give interviewees seems to trip them up all the time, and I wonder if I'm being too much of a hardass... it seems easy enough to ME, but these guys, when I get them up to the whiteboard, seem to get really confused. The exercise is this:
10
1889
by: Gopal Krish | last post by:
I was asked this question in an interview. How can you display the contents of an ASP page (from another web server) in a aspx page, ie, first half of the screen will display contents from asp and the other half will be from the current aspx page. Using frames is not an option. Any thoughts? (Is this even possible?)
0
6171
by: Jobs | last post by:
Download the JAVA , .NET and SQL Server interview sheet and rate yourself. This will help you judge yourself are you really worth of attending interviews. If you own a company best way to judge if the candidate is worth of it. http://www.questpond.com/InterviewRatingSheet.zip 2000 Interview questions of .NET , JAVA and SQL Server Interview questions (worth downloading it)
2
6971
by: Jobs | last post by:
Download the JAVA , .NET and SQL Server interview with answers Download the JAVA , .NET and SQL Server interview sheet and rate yourself. This will help you judge yourself are you really worth of attending interviews. If you own a company best way to judge if the candidate is worth of it. http://www.questpond.com/InterviewRatingSheet.zip
0
4605
by: connectrajesh | last post by:
INTERVIEWINFO.NET http://www.interviewinfo.net FREE WEB SITE AND SERVICE FOR JOB SEEKERS /FRESH GRADUATES NO ADVERTISEMENT
18
2869
by: Nobody | last post by:
I've been looking for a job for a while now, and have run into this interview question twice now... and have stupidly kind of blown it twice... (although I've gotten better)... time to finally figure this thing out... basically the interview question is: given an unsorted listed such as: 3,1,3,7,1,2,4,4,3 find the FIRST UNIQUE number, in this case 7... and of course the list can be millions long...
2
7230
by: freepdfforjobs | last post by:
Full eBook with 4000 C#, JAVA,.NET and SQL Server Interview questions http://www.questpond.com/SampleInterviewQuestionBook.zip Download the JAVA , .NET and SQL Server interview sheet and rate yourself. This will help you judge yourself are you really worth of attending interviews. If you own a company best way to judge if the candidate is worth of it. http://www.questpond.com/InterviewRatingSheet.zip
0
2671
by: freesoftwarepdfs | last post by:
Ultimate list of Interview question website.....Do not miss it http://www.questpond.com http://msdotnetsupport.blogspot.com/2007/01/net-interview-questions-by-dutt-part-2.html http://msdotnetsupport.blogspot.com/2006/08/net-windows-forms-interview-questions.html http://msdotnetsupport.blogspot.com/2006/08/net-remoting-interview-questions.html http://msdotnetsupport.blogspot.com/2006/08/c-interview-questions.html...
0
2236
by: Free PDF | last post by:
..NET , SQL Server interview questions websites.... http://www.questpond.com http://www.geocities.com/dotnetinterviews/ http://msdotnetsupport.blogspot.com/2007/01/net-interview-questions-by-dutt-part-2.html http://msdotnetsupport.blogspot.com/2006/08/net-windows-forms-interview-questions.html http://msdotnetsupport.blogspot.com/2006/08/net-remoting-interview-questions.html...
0
9731
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9605
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10136
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9208
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5556
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5697
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4342
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3871
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3020
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 can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.