I could do this in C#..
int number = 2;
string str = "Hello " + number + " world";
..and str ends up as "Hello 2 world".
In VB.NET i could do this..
Dim number As Integer = 2
Dim str As String = "Hello " + number + " world"
..but I get an InvalidCastException "Conversion from string "Hello " to type 'Double' is not valid."
I am aware that I should use .ToString() in both cases, but whats going on here with the code as it is?
In VB I believe the string concatenation operator is & rather than + so try this:
Dim number As Integer = 2
Dim str As String = "Hello " & number & " world"
Basically when VB sees + I suspect it tries do numeric addition or use the addition operator defined in a type (or no doubt other more complicated things, based on options...) Note that System.String doesn't define an addition operator - it's all hidden in the compiler by calls to String.Concat. (This allows much more efficient concatenation of multiple strings.)
Visual Basic makes a distinction between the + and & operators. The & will make the conversion to a string if an expression is not a string.
&Operator (Visual Basic)
The + operator uses more complex evaluation logic to determine what to make the final cast into (for example it's affected by things like Option Strict configuration)
+Operator (Visual Basic)
I'd suggest to stay away from raw string concatenation, if possible.
Good alternatives are using string.format:
str = String.Format("Hello {0} workd", Number)
Or using the System.Text.StringBuilder class, which is also more efficient on larger string concatenations.
Both automatically cast their parameters to string.
The VB plus (+) operator is ambiguous.
If you don't have Option Explicit on, if my memory serves me right, it is possible to do this:
Dim str = 1 + "2"
and gets str as integer = 3.
If you explicitly want a string concatenation, use the ampersand operator
Dim str = "Hello " & number & " world"
And it'll happily convert number to string for you.
I think this behavior is left in for backward compatibility.
When you program in VB, always use an ampersand to concatenate strings.
Related
I have a string variable as below:
string testVar = "abc ";
Then I have a if statement as below:
if(this.testVar[this.testVar.Length-1].Equals(" "))
From the above I'm trying to find if the last character is space, if it is space then do something. But it is always false even if my testVar = "abc "?
testVar[…] returns a char, not a string. That’s why an Equals test with a string always returns false. You can fix this easily by comparing to a char. you also don’t need Equals:
if (testVar[testVar.Length - 1] == ' ')
It is worth nothing that, if you had used == initially instead of Equals, you would have gotten a compile time error explaining the problem. This illustrates nicely why it’s good to use early binding rather than late binding (Equals takes an object and hence doesn’t offer compile-time type checking).
Why do you not just use:
if (testVar.EndsWith (" "))
It is always false because a char is never equal to a string.
This would work:
if (this.testVar[this.testVar.Length-1].Equals(' '))
or this
if (this.testVar[this.testVar.Length-1] == ' ')
check this dude
var result = str.Substring(str.LastIndexOf(' ') + 1);
Let's face following code :
string a = "This is not a long string!";
string b = "Another string";
b = "This is" + " not a long " + "string" + "!";
Console.WriteLine(object.ReferenceEquals(a, b)); //True !
string c = "This is" + " not a long " + "string" + '!';
Console.WriteLine(object.ReferenceEquals(a, c)); //False
The only reason I see is that .NET has optimized variables to take less space.
Does .NET store strings with zero terminated[null] or string length ?
I mean when I write following code is it possible to lose the part after the null char if .NET run optimization against the string ?
string Waaaa = "This is not \0a long string!";
Strings in .NET are in essence character arrays - char[] (where char is a representation of a UTF-16 character). They are not C strings - they are not null terminated.
What you see is the result of string interning - any string literal will get interned (and the compiler is smart enough to know to convert concatenated strings to a single literal).
Your Waaaa variable will be exactly what you have posted - with a null character in the middle.
Assume I have the following string constants:
const string constString1 = "Const String 1";
const string constString2 = "Const String 2";
const string constString3 = "Const String 3";
const string constString4 = "Const String 4";
Now I can append the strings in two ways:
Option1:
string resultString = constString1 + constString2 + constString3 + constString4;
Option2:
string resultString = string.Format("{0}{1}{2}{3}",constString1,constString2,constString3,constString4);
Internally string.Format uses StringBuilder.AppendFormat. Now given the fact that I am appending constant strings, which of the options (option1 or option 2) is better with respect to performance and/or memory?
The first one will be done by the compiler (at least the Microsoft C# Compiler) (in the same way that the compiler does 1+2), the second one must be done at runtime. So clearly the first one is faster.
As an added benefit, in the first one the string is internalized, in the second one it isn't.
And String.Format is quite slow :-) (read this
http://msmvps.com/blogs/jon_skeet/archive/2008/10/06/formatting-strings.aspx). NOT "slow enough to be a problem", UNLESS all your program do all the day is format strings (MILLIONS of them, not TENS). Then you could probably to it faster Appending them to a StringBuilder.
The first variant will be best, but only when you are using constant strings.
There are two compilator optimizations (from the C# compiler, not the JIT compiler) that are in effect here. Lets take one example of a program
const string A = "Hello ";
const string B = "World";
...
string test = A + B;
First optimization is constant propagation that will change your code basically into this:
string test = "Hello " + "World";
Then a concatenation of literal strings (as they are now, due to the first optimization) optimization will kick in and change it to
string test = "Hello World";
So if you write any variants of the program shown above, the actual IL will be the same (or at least very similar) due to the optimizations done by the C# compiler.
I am sure this is a simple question for you guys but I don't know what this developer is doing.
name = String.Format(MyStringBuilder + "");
If I convert this to VB I get the message "operator + is not defined for types system.text.stringbuilder and string". Same thing if I use &.
It looks as if the person who wrote it is attempting to force an implicit conversion of MyStringBuilder to a string using the + operator in conjuction with the empty string.
To perform this assignment in VB you only need:
name = MyStringBuilder.ToString()
In the strictest sense, MyStringBuilder in the original code could be a null instance, at which point making an explicit call to .ToString() would throw an exception. The code sample provided would execute properly, however. In VB, you may want to say
Dim name As String
If MyStringBuilder Is Nothing Then
name = String.Empty
Else
name = MyStringBuilder.ToString()
End If
That doesn't make sense to me because AFAICT passing only one argument to string.format doesn't do anything.
Adding "" to the stringbuilder just coerces it to a string.
name = MyStringBuilder.ToString(); would be how I'd do this in C#. Converting that statement to VB should be loads easier.
Use MyStringBuilder.ToString(). That will fix the problem.
You're trying to concatenate a StringBuilder object and String together - that wouldn't work :)
name = String.Format(MyStringBuilder.ToString() + "");
This should compile correctly.
In VB.NET you would use a "&" instead of a "+"
This line:
name = String.Format(MyStringBuilder + "");
Is causing an implicit cast of MyStringBuilder to string (using the ToString() method) in order to use the "+" operator. It's the same as:
name = String.Format(MyStringBuilder.ToString() + "");
which is the same as
name = MyStringBuilder.ToString();
which becomes this in VB.NET:
name = MyStringBuilder.ToString()
I know you should use a StringBuilder when concatenating strings but I was just wondering if there is a difference in concatenating string variables and string literals. So, is there a difference in performance in building s1, s2, and s3?
string foo = "foo";
string bar = "bar";
string s1 = "foo" + "bar";
string s2 = foo + "bar";
string s3 = foo + bar;
In the case you present, it's actually better to use the concatenation operator on the string class. This is because it can pre-compute the lengths of the strings and allocate the buffer once and do a fast copy of the memory into the new string buffer.
And this is the general rule for concatenating strings. When you have a set number of items that you want to concatenate together (be it 2, or 2000, etc) it's better to just concatenate them all with the concatenation operator like so:
string result = s1 + s2 + ... + sn;
It should be noted in your specific case for s1:
string s1 = "foo" + "bar";
The compiler sees that it can optimize the concatenation of string literals here and transforms the above into this:
string s1 = "foobar";
Note, this is only for the concatenation of two string literals together. So if you were to do this:
string s2 = foo + "a" + bar;
Then it does nothing special (but it still makes a call to Concat and precomputes the length). However, in this case:
string s2 = foo + "a" + "nother" + bar;
The compiler will translate that into:
string s2 = foo + "another" + bar;
If the number of strings that you are concatenating is variable (as in, a loop which you don't know beforehand how many elements there are in it), then the StringBuilder is the most efficient way of concatenating those strings, as you will always have to reallcate the buffer to account for the new string entries being added (of which you don't know how many are left).
The compiler can concatenate literals at compile time, so "foo" + "bar" get compiled to "foobar" directly, and there's no need to do anything at runtime.
Other than that, I doubt there's any significant difference.
Your "knowledge" is incorrect. You should sometimes use a StringBuilder when concatenating strings. In particular, you should do it when you can't perform the concatenation all in one experession.
In this case, the code is compiled as:
string foo = "foo";
string bar = "bar";
string s1 = "foobar";
string s2 = String.Concat(foo, "bar");
string s3 = String.Concat(foo, bar);
Using a StringBuilder would make any of this less efficient - in particular it would push the concatenation for s1 from compile time to execution time. For s2 and s3 it would force the creation of an extra object (the StringBuilder) as well as probably allocating a string which is unnecessarily large.
I have an article which goes into more detail on this.
There is no difference between s2 and s3. The compiler will take care of s1 for you, and concatenate it during compile time.
I'd say that this should decide compiler. Because all your string-building can be optimized as values is already known.
I guess StringBuilder pre-allocates space for appending more strings. As You know + is binary operator so there is no way to build concatenation of more than two strings at a time. Thus if you want to do s4 = s1 + s2 + s3 it will require building intermediate string (s1+s2) and only after that s4.