c# - "stringDemo" versus new string("stringDemo".ToCharArray); -
please @ below code:
using system; class myclass { static void main() { object o = ".net framework"; object o1 = new string(".net framework".tochararray()); console.writeline(o == o1); console.writeline(o.equals(o1)); } } and result is:
false
true
and consider one:
using system; class myclass { static void main() { object o = ".net framework"; object o1 = ".net framework"; console.writeline(o == o1); console.writeline(o.equals(o1)); } } and result is:
true
true
“==” compares if object references same while “.equals()” compares if contents same. , want know different between these codes?!
object o1 = new string(".net framework".tochararray()); and
object o1 = ".net framework"; both of them turn out object why results different?
both of them turn out object why results different?
in second case, you're using same string constant both o , o1 assignment. c# guarantees 2 equal string constant expressions within same program refer same string object. values of o , o1 same reference.
while can't find more general form (for constant string expressions), case covered section 2.4.4 of c# spec:
when 2 or more string literals equivalent according string equality operator appear in same program, these string literals refere same string instance.
edit: quick note on behaviour of ==:
- if both operands have compile-time type of
==, overload providedstringused, performs content comparison - otherwise, "default" implementation compares references equality used, stated in question.
in case, compile-time types of operands both object, genuinely using reference equality.
Comments
Post a Comment