|
Strings are reference types, but string comparisons are made as value types:
string a = "Hello World";
string b = "Hello";
string c = " World";
string d = b + c;
Console.WriteLine("{0}:{1}:{2}:{3}", a == d, a.Equals(d), (object)a == (object) d, object.ReferenceEquals(a, d));
Will give you:
True:True:False:False Because the first two tests use the string specific comparison, and the other two specifically do reference comparisons.
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
With strings, there is another fact to consider. When the compiler can detect that they have the same value, the compiler will make sure that they have the same reference also. It can do that optimization because strings are immutable.
In the example given by OriginalGriff, the compiler did not detect that and thus the compiler created two different references.
Oh sanctissimi Wilhelmus, Theodorus, et Fredericus!
|
|
|
|
|
That's where it gets complicated (and why I didn't mention it - he is a beginner, after all).
The compiler can detect and intern strings, but the runtime doesn't unless you specifically ask it to:
string a = "Hello World";
string b = "Hello";
string c = " World";
string d = b + c;
Console.WriteLine("{0}:{1}:{2}:{3}", a == d, a.Equals(d), (object)a == (object)d, object.ReferenceEquals(a, d));
d = string.Intern(d);
Console.WriteLine("{0}:{1}:{2}:{3}", a == d, a.Equals(d), (object)a == (object)d, object.ReferenceEquals(a, d));
Will give you:
True:True:False:False
True:True:True:True As the "new" string is now in the Intern pool.
However ... in the release version of my original code you will probably get different results, as the optimiser will likely compact that code and intern the strings anyway!
There is a good description of the intern pool here: Understanding C#: String.Intern makes strings interesting - O'Reilly Broadcast[^]
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
i have a very small question sir.
string a = "Hello World";
string b = "Hello World";
when we compare like if(a==b) then what will happen?
== operator compare by value or reference ?
when two string variable having same value and if == operator compare by vale then why value is checked by reference ?
please help me to understand this small area. thanks a lot in advance sir.
|
|
|
|
|
At this stage, I'd say "don't worry about it" - because it starts to get pretty complicated. When you write code like that, two additional factors come into play: optimisation and interning.
Optimisation is not normally applied to debug builds - they are optimised for "debuggability" not performance and that means that large sections of the compiler do not get used that can make significant changes to your code. For example, the compiler can look at this:
public bool IsSame()
{
string a = "Hello World";
string b = "Hello World";
return a == b;
} And "know" that it will always produce the same result: true. So the compiler can "throw away" the whole method and replace it with inline code for "true" wherever your code references it.
That makes it very difficult to say "it's this type of comparison" because the comparison may never occur at all, depending on what happens in the surrounding code! It doesn't do that for debug builds, because it makes it a lot harder for you the developer to work with in the debugger - you can't set a breakpoint on code which has been optimised out!
Interning is another complexity, and one I was hoping to avoid - and why I wrote my original code exactly the way I did. Interning basically means that because strings are immutable, the compiler "knows" that the two string literals are the same, so it only ever keeps one copy of it. So the comparison changes: it becomes a comparison between two identical references, so the question of "value or reference comparison?" becomes moot: they are the same. To see what I mean, try modifying my original code:
string a = "Hello World";
string b = "Hello";
string c = " World";
string d = b + c;
string e = "Hello World";
Console.WriteLine("{0}:{1}:{2}:{3}", a == d, a.Equals(d), (object)a == (object)d, object.ReferenceEquals(a, d));
Console.WriteLine("{0}:{1}:{2}:{3}", a == e, a.Equals(e), (object)a == (object)e, object.ReferenceEquals(a, e)); Run that, and you will get different results for the two WriteLines:
True:True:False:False
True:True:True:True The strings have been interned, so the references are the same.
If you want to know more - and this stuff can get quite complicated - I'd point you are the same link I did Bernhard: Understanding C#: String.Intern makes strings interesting - O'Reilly Broadcast[^] - but to be honest, this isn't stuff you need to know 99% of the time as it makes absolutely no different to how you code your app!
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Sir i was asked in interview that if we execute this code a==b then will it be compare by value or reference ? i said value and they told me nothing. i guess i was wrong.
so tell me when we compare a==b does this comparison occur by value or ref if two string variable having same data. thanks
|
|
|
|
|
If both variables are declared as string , then it compares by value.
Determines whether two specified strings have the same value.
public static bool operator == (String a, String b) {
return String.Equals(a, b);
}
public static bool Equals(String a, String b) {
if ((Object)a==(Object)b) {
return true;
}
if ((Object)a==null || (Object)b==null) {
return false;
}
if (a.Length != b.Length)
return false;
return EqualsHelper(a, b);
}
(Where EqualsHelper[^] essentially compares the strings character by character, but using unsafe code to improve the performance.)
If either variable is declared as object , then it will compare by reference.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
it seems to me that if check two string variable
String.Equals(a, b); OR a == b then it will be checking by value but if i check this way
if ((Object)a==(Object)b) then this type of checking is done by reference.
do i understand properly now ? am i right now ?
|
|
|
|
|
Yes, that's correct.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
thanks you sir for your great help.
|
|
|
|
|
For a string, a == b is always a value comparison, but ... it starts with a reference comparison!
1) operator == calls string.Equals.
2) The first thing that Equals does is this:
if ((Object)a==(Object)b) return true;
Which is a reference comparison, as you'd expect. A good percentage of the time, this will make the process faster.
3) It then checks for null in either side, and returns false if either is null.
4) It then compares the lengths - any difference is a return false.
5) It then calls another method which repeats those two tests (if it's the debug build) and throws an exception via Contract.Requires
6) It then uses unsafe code with pointers to do a value comparison (but quickly, using 12 bytes at a time for AMD processors, and 10 for Intel - don't ask)
So technically, "a == b" is a value comparison, but it has a few additional tests to speed things up, including a reference comparison.
But you really aren't supposed to know that, the traditional answer is "value comparison for strings". It may be that they wanted you to expand on "value type" and maybe explain why it's not a reference comparison?
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Wow, my reply in the interview would have been "I don't know, nor do I care". It must be a specialised requirement if this depth of knowledge is required for the position (I do LOB apps only).
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
You should probably care about the value type comparison that is specific to strings - it does affect performance after all. And knowing that release optimisation could change how things work could be important.
But interning strings - particularly at run time - you don't normally need to know about. (The compile time interning is pretty much irrelevant as it's a "side effect" of immutability.)
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Dear All,
I have an unmanaged DLL developed by Delphi language and it's support 86x and 64x and I want to use the DLL in my c# windows form application which use any cpu as a platform target but this error occurred
"System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)
at ScaleDLL.frmMain.AclasSDK_Initialize(Pointer Adjuct)
at ScaleDLL.frmMain.frmMain_Load(Object sender, EventArgs e) in F:\Dot Net Projects\Dlls\ScaleDLL\ScaleDLL\frmMain.cs:line 147"
and we can't change the platform target to 86x because we use other libraries and it is not work when change the platform and we need to use this dll on the AnyCpU platform.
Please help me ASAP.
Thank You
|
|
|
|
|
It's not simple, not at all.
Because you are using 64 bit libraries already, you can't access 32 bit libraries on the same process - even if you compile for "any cpu" that doesn't mean that a process can "switch" dynamically between the two.
If you want to cleanly use your legacy DLL, you will need to either convert everything else to x86, convert the legacy DLL to 64 bit, or ... start reading: Accessing 32-bit DLLs from 64-bit code | Reflections on IT[^] Do not expect this to be a clean, neat, and easy solution.
And no, I've never needed to do it - so I can't help you here...
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
|
Hi!how to create wordsearch in c#?
|
|
|
|
|
With classes, some variables, methods and a whole host of semi-colons. Hopefully you'll throw some algorithms in there as well.
This space for rent
|
|
|
|
|
|
|
|
Your answer is contained in the text below:
bxIpOAZvrvLsWNTKAecZLbZZHkmgjiEuZxaHyGwzfSTrtdAHFRBBIoFqvncYZnJMQbxFaCJmIulOTsQU
WDmQMnhsEBqnmIEvfYVqFBirsSJhHIYYRkqNajTeWDAxVKkuxSPbHiaHHyrOWjdlFjQhmBRdfnjqaEPd
FXgEJBraarSxWmaYuJPBaRCgDszOoKfDfCQvvPJmehLfTCCjcwzOPopWQiqMxWKnhEdxEBrLdOFNJMsp
thwrEmkUNpuwsYaJPOfgVpxbBcuStoSVcdkLegIBSsFdbZkuFsdpwvlGttRXAagoPQvMjaMFhvKkwXex
WYhUEedrZTdKlzIIWqWgLDMKLOnVwaawcOShcnlUwfbZXyFiwxqcfFrtVVczjPaFQYpnMBLYVUIPDCuu
ZXzobkLrcUkvxfVPUJfYquzekEt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uDBIofLkfUBkAYKThJkoaIWXZbyAUmubYCVnZvyPKNfOHUNoYOLZIIUjAgwKZUKcebfG
ZQzTnKxwWdQkCtkvJCBWcHnTIrkehwYXtcPHUXlyAgwIunMZhEREcQlBStqjRosfjCRkiJOrVhiMJkQC
YyYomrZsIPqmkizQAbCkQNzEfPRircNLbWXpMbhwcTECKXeFTlvvMtQlzKLRADhUuhgurwuBwmbffIyI
MHLPRMkgsQvyIwYWKxgFzebmDiWYcrWIZvyroegTvHMuVFEvKwyXPZpHOpGXEmqdmQFLVHUzwRxyTtIh
hhKXodSTKEWLdbfOvVFuirWsGFZgfMdqPtvIwmeDwWLYWVuIktUJiQWuNMZpvJAvkiqtbShdITxYDOrr
xqKexxQkkAgwVmbLMrfWLYtuzOkrjAFMxbREyqHzrNvtCDHgNKWzHFSjgtfDrOCVamABgDbVZslVDLuj
=========================================================
I'm an optoholic - my glass is always half full of vodka.
=========================================================
|
|
|
|
|
Step 1: follow the question/answer guidelines of the forum (first 2 posts of each forum)
For those new to message boards please try to follow a few simple rules when posting your question.
Choose the correct forum for your message. Posting a VB.NET question in the C++ forum will end in tears.
Be specific! Don't ask "can someone send me the code to create an application that does 'X'. Pinpoint exactly what it is you need help with.
Keep the subject line brief, but descriptive. eg "File Serialization problem"
Keep the question as brief as possible. If you have to include code, include the smallest snippet of code you can.
Be careful when including code that you haven't made a typo. Typing mistakes can become the focal point instead of the actual question you asked.
Do not remove or empty a message if others have replied. Keep the thread intact and available for others to search and read. If your problem was answered then edit your message and add "[Solved]" to the subject line of the original post, and cast an approval vote to the one or several answers that really helped you.
If you are posting source code with your question, place it inside < p r e > < / p r e > tags. We advise you also check the "Encode "<" (and other HTML) characters when pasting" checkbox before pasting anything inside the PRE block, and make sure "Use HTML in this post" check box is checked.
Be courteous and DON'T SHOUT. Everyone here helps because they enjoy helping others, not because it's their job.
Please do not post links to your question into an unrelated forum such as the lounge. It will be deleted. Likewise, do not post the same question in more than one forum.
Do not be abusive, offensive, inappropriate or harass anyone on the boards. Doing so will get you kicked off and banned. Play nice.
If you have a school or university assignment, assume that your teacher or lecturer is also reading these forums.
No advertising or soliciting.
We reserve the right to move your posts to a more appropriate forum or to delete anything deemed inappropriate or illegal.
|
|
|
|
|
I've read that it's not a good idea to fire an sync method from a property, yet I see plenty of places where I would want to do this.
For example, at the top of my Contacts view I have a Search field bound to a ContactSearchValue string property. When the user enters a seaarch value I reload all the contacts that match.
To do this I call LoadContacts from the settter of the property. Because LoadContacts is async I get a compilation warning saying "Because this call is not awaited, execution of the current method continues before the call is completed" This is OK beause it in a property settings and there's no other code.
Anyone have any thoughts on this?
If it's not broken, fix it until it is.
Everything makes sense in someone's mind.
Ya can't fix stupid.
|
|
|
|
|
It is not a good idea because it is fire-and-forget. Unit-testing this kind of code is a pain or plainly not possible.
But yes you can do it... Just be aware of the bad stuff that may happen.
|
|
|
|
|