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()
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);
I want to do the following but I get this
Error: an Implicit conversion from type Char[] to string is not
possible.
string Pattern2 = (Convert.ToDateTime(currMail.CreationTime).ToString(" dd-MMM-yyyy HH-mm")).ToArray();
Does anybody have any idea as on how to deal with this?
Remove .ToArray():
string Pattern2 = Convert.ToDateTime(currMail.CreationTime).ToString("dd-MMM-yyyy HH-mm");
As the other answers point out, your call to ToArray is not just unnecessary, it is in this case actively harmful. You already have a string in hand, you need a string, so don't convert the string to an array of char; just use the string.
However, for your future reference it is possible to convert an array of char to a string, just not via an implicit or explicit conversion. The syntax for that is:
char[] characters = whatever;
string str = new String(characters);
Finally, the documentation is here:
http://msdn.microsoft.com/en-us/library/vstudio/s1wwdcbf.aspx
Beginners should familiarize themselves with this documentation; there's a lot of good stuff in there.
Looks like you don't need to use .ToArray() method at all. You already using .ToString() method for assigning to your Pattern2 variable.
Just use as;
string Pattern2 = Convert.ToDateTime(currMail.CreationTime).ToString("dd-MMM-yyyy HH-mm");
string Pattern2 = Convert.ToDateTime(currMail.CreationTime).ToString(" dd-MMM-yyyy HH-mm");
You assign a char[] to a string, which requires conversion from the char[] to a string. As the error says, this is not done implicitly, i.e. behind the scenes. This is done to prevent silly mistakes.
You are expected to make an explicit conversion (create a string from the array and then assign it).
In your case you have a string and convert it to an array before assigning it to Pattern2. Just don't convert the string to an array.
string Pattern2 = (Convert.ToDateTime(currMail.CreationTime).ToString(" dd-MMM-yyyy HH-mm"));
Can I pass a C# string variable into an xpath selector? This is for a selenium unit test. I want to do something like this:
string myText = "foo";
Assert.IsTrue(Browser.IsElementPresent("//option[contains(text(), $myText)]"));
Using a string.Format should work:
Assert.IsTrue(Browser.IsElementPresent(string.Format("//option[contains(text(), {0}]",myText)));
yes you can use String.Format
string myText = "foo";
Assert.IsTrue(Browser.IsElementPresent(String.Format("//option[contains(text(), {0})]", myText)));
I see this has already been answered but you could also just do:
Assert.IsTrue(Browser.IsElementPresent(String.Format("//option[contains(text(), " + myText + ")]")));
This works because C# will just append each string to the end of the other.
Thank you for your answers! I was doing a Find in a table, and the above solutions did not work for me, possibly because my string contained hyphens, a decimal point, and numerals like so: "TV-8888-ZIP-54-EN-CTR.05021031"
I assigned the string to the C# variable ID. The answers above failed, I suspect, due to the decimal point and numerals. Using Nashibukasan's answer, I had to explicitly add single quotes. The working Find statement--that gets the value in the third column of the table from the same row that contains the ID string in the first column--ended up looking like this:
value = driver.FindElement(By.XPath(string.Format("//td[contains(text()," + "'" + ID + "'" + ")]/following-sibling::td[2]"))).Text;
I am trying to read a string into an array and I get the error "Cannot implecitly convert type 'string' to 'string[]'.
The error occurs here:
string[] sepText = result.Tables[0].Rows[0].Field<string>("WebHTML").UrlDecode();
My full if else statement is below:
if (!string.IsNullOrEmpty(result.Tables[0].Rows[0].Field<string>("WebHTML")))
{
string[] sepText = result.Tables[0].Rows[0].Field<string>("WebHTML").UrlDecode();
NewsContent.Text = sepText[1];
if (!string.IsNullOrEmpty(sepText[0]))
Image1.ImageUrl = sepText[0];
else
Image1.Visible = false;
NewsTitle.Text = String.Format("{3}", Extensions.GetServerName(true), result.Tables[0].Rows[0].Field<int>("News_Item_ID"), result.Tables[0].Rows[0].Field<string>("Title").UrlFormat(), result.Tables[0].Rows[0].Field<string>("Title"));
Hyperlink1.NavigateUrl = String.Format("{0}/news/{1}/{2}.aspx", Extensions.GetServerName(true), result.Tables[0].Rows[0].Field<int>("News_Item_ID"), result.Tables[0].Rows[0].Field<string>("Title").UrlFormat());
}
else
{
Hyperlink1.Visible = false;
Image1.Visible = false;
}
Thank you for your help!
EDIT Code for URL Decode:
public static string UrlDecode(this string str)
{
return System.Web.HttpUtility.UrlDecode(str);
}
result.Tables[0].Rows[0].Field<string>("WebHTML") is going to give you the value of the WebHTML field in the first row in the first table which is a single string rather than a string[].
You may want to show your code for UrlDecode() since it looks like a custom implementation rather than one of the built-in framework versions.
You also declare the UrlDecode method to take a string as a parameter and return a string. Remember, a string is not the same thing as a string array.
It seems that you are trying to put:
result.Tables[0].Rows[0].Field<string>("WebHTML").UrlDecode();
which returns a string, into an array of strings.
Simply delare your sepText variable as a string rather than a string array and you should be good to go, e.g.:
string sepText = result.Tables[0].Rows[0].Field<string>("WebHTML").UrlDecode();
Later in your code you will clearly need to read the contents of the string like this:
Image1.ImageUrl =sepText;
Assuming the UrlDecode you are using is the one from here then the result is a string and not a string[] !
UrlDecode returns a string and you are assigning it to an array.
If you want the parts you will have to use the string to create an Url object.
Url url = new Url(result.Tables[0].Rows[0].Field<string>("WebHTML"));
and then get the parts.
See: Get url parts without host
I don't think URLDecode works the way you think it works. All URLDecode does is remove URL encoding from a string. It does not return an array of strings - only the decoded value of the string you gave it.
http://msdn.microsoft.com/en-us/library/system.web.httputility.urldecode.aspx
Example: Your web browser replaces a space with %20. This changes the %20 back to a space.
That's because the result of this line is "string" and you're trying to assign it to an array since UrlDecode do not produce an array. What you probably wanted is to use a method split() to create an array of separators?
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.