What is equivalent to VB.NET's Length keyword in C#? - c#

I wrote VB.NET code like this:
d = Data.IndexOf("</a>", ("target='_top' class='ab1'>").Length() + s).
I want to write this in C#. When I wrote the above code in C#, it said there was an error with the Length keyword. How do I write the above code in C#?

Length is not a keyword in C# - it is either a property or an extension method on the object (like a string) that you are trying to manipulate.
So if it is a string you are using this will work:
myString.Length
(notice how the brackets are missing because it is a property).

You have an extra set of parentheses:
d = Data.IndexOf("</a>", "target='_top' class='ab1'>".Length + s)
Try that

Check this link out:
In it, you can easliy switch between C# to a VB good, to help you migrate:
http://msdn.microsoft.com/en-us/library/system.string.length.aspx#Y242

Related

Matching and replacing function expressions

I need to do some very light parsing of C# (actually transpiled Razor code) to replace a list of function calls with textual replacements.
If given a set containing {"Foo.myFunc" : "\"def\"" } it should replace this code:
var res = "abc" + Foo.myFunc(foo, Bar.otherFunc( Baz.funk()));
with this:
var res = "abc" + "def"
I don't care about the nested expressions.
This seems fairly trivial and I think I should be able to avoid building an entire C# parser using something like this for every member of the mapping set:
find expression start (e.g. Foo.myFunc)
Push()/Pop() parentheses on a Stack until Count == 0.
Mark this as expression stop
replace everything from expression start until expression stop
But maybe I don't need to ... Is there a (possibly built-in) .NET library that can do this for me? Counting is not possible in the family of languages that RE is in, but maybe the extended regex syntax in C# can handle this somehow using back references?
edit:
As the comments to this answer demonstrates simply counting brackets will not be sufficient generally, as something like trollMe("(") will throw off those algorithms. Only true parsing would then suffice, I guess (?).
The trick for a normal string will be:
(?>"(\\"|[^"])*")
A verbatim string:
(?>#"(""|[^"])*")
Maybe this can help, but I'm not sure that this will work in all cases:
<func>(?=\()((?>/\*.*?\*/)|(?>#"(""|[^"])*")|(?>"(\\"|[^"])*")|\r?\n|[^()"]|(?<open>\()|(?<-open>\)))+?(?(open)(?!))
Replace <func> with your function name.
Useless to say that trollMe("\"(", "((", #"abc""de((f") works as expected.
DEMO

VB to C# how to convert if param and 1

I'm converting some VB code in C#, i have this if sentence
if param and 1 then
...
end if
i don't get how to convert this in C# (btw param is a short), is this something related to power of 2? How can i convert this?
You need to write this as a boolean expression:
if ((param & 1) != 0)
{
..
}
I would use a code convert to migrate you code across try the following site:
http://converter.telerik.com/

Equivalent of Format of VB in C#

What will be the equivalent code for Format(iCryptedByte, "000") (VB.NET) in C# ?
String.Format(format, iCryptedByte); // where format like {0:D2}
See MSDN 1, 2, 3
Another very useful site for C# string formatting: http://blog.stevex.net/string-formatting-in-csharp/
Instead of {0:D3} you can also use the zero placeholder, e.g. {0:000} will pad with zeros to minimum length of three.
Microsoft.VisualBasic.Strings.Format(iCryptedByte, "000");
You'll need to add a reference to the Microsoft.VisualBasic assembly.
Given this VB code:
Strings.Format(iCryptedByte, format)
Replace with this C# code:
var csformat = "{0:" + format + "}";
String.Format(csformat, iCryptedByte);
Try:
iCryptedByte.ToString("D3");
see String.Format

how to get a String with String.Format to execute?

I have a little chunk of code (see below) that is returning the string:
string.Format("{0}----{1}",3,"test 2");
so how do I get this to actually "Execute"? To run and do the format/replacement of {0} and {1}?
My Code snippet:
StringBuilder sb = new StringBuilder();
sb.Append("{0}----{1}\",");
sb.AppendFormat(ReturnParamValue(siDTO, "siDTO.SuggestionItemID,siDTO.Title"));
string sbStr = "=string.Format(\""+sb.ToString()+");";
yes, ReturnParamValue gives the actually value of the DTO.
Anyways, I've taken a look at the following (but it doesn't say how to execute it:
How to get String.Format not to parse {0}
Maybe, I just should put my code snippet in a method. But, what then?
Why are you including String.Format in the string itself?
If you're looking for a generic "let me evaluate this arbitrary expression I've built up in a string" then there isn't a simple answer.
If, instead, you're looking at how to provide the parameters to the string from a function call, then you've got yourself all twisted up and working too hard.
Try something like this, based on your original code:
string result
= string.Format(
"{0}----{1}",
ReturnParamValue(siDTO, "siDTO.SuggestionItemID,siDTO.Title"));
Though, this won't entirely work since your original code seems to be only providing a single value, and you have two values in your format string - the {0} will be replaced with the value from your function, and {1} left unchanged.
What output are you expecting?
Does your ReturnParamValue() function try to return both the label and the value in a single string? If it does, and if they're comma separated, then you could try this:
var value = ReturnParamValue(siDTO, "siDTO.SuggestionItemID,siDTO.Title"));
var pieces = string.Split(',');
string result
= string.Format( "{0}----{1}", pieces[0], pieces[1]);
Though this is seriously working too hard if ReturnParamValue() is a method you control.
Update Fri 6 August
Check out the declaration for string.Format() as shown on MSDN:
public static string Format(
string format,
params Object[] args
)
Unlike the special casing you might have seen in C for printf(), there's nothing special or unusual about the way string.Format() handles multiple parameters. The key is the params keyword, which asks the compiler to provide a little "syntactic sugar" where it combines the parameters into an array for you.
Key here is that the wrapping doesn't happen if you're already passing a single object[] - so if you wanted to, you could do something like this:
object[] parameters
= ReturnParamValues(siDTO, "siDTO.SuggestionItemID,siDTO.Title");
string result
= string.Format("{0}----{1}----{2}", parameters);
Though, if I saw something like this in any codebase I maintained, I'd be treating it as a code-smell and looking for a better way to solve the problem.
Just because it's possible doesn't mean it's advisable. YMMV, of course.
I don't think you can execute it. Java is not really a interpreted language.
You may make use of scripting languages (which can even embed in your Java app as I know, start from JDK6) for such purpose, like Groovy
You could use RegEx to parse the three parameters out of the string, and then pass them to a real, actual string.Format method :-)
It looks like what you want is something like this:
string sbStr = string.Format("{0}----{1}", siDTO.SuggestionItemID, siDTO.Title);
Maybe i didn't understand your question completely, but it sounds like you need to format a format-string. If that's true you could maybe try something like this:
int width = 5;
string format = String.Format("{{0,{0}}}----{{1,{0}}}", width);
string result = String.Format(format, "ab", "cd");
So the trick is simply to escape the { or } by using a double {{ or }}.

In C# VS2008 how to replace (string)aaa to aaa.ToString()

I just converted a VB.net solution into C# solution. But lots of variables have been coverted like:
string var1 = (string)1;
string var2 = (string)intVar; //intVar is a int value
I just want to convert all (string)XXXX to XXXX.ToString() by using some Regular expressions or some other replace methods.
Can someome help me out?
find: \(string\){:a*}
replace: \1.ToString()
Back up your solution first!
The text editor Notepad++ has regular expression support. You may try something like: Replace [(]string[)][ ]*([^ .\t;/]*) with \1.ToString().
This turns this:
(string) xyz;
(string) abc.123;
(string)alf;
(string)argu ment
into this:
xyz.ToString();
abc.ToString().123;
alf.ToString();
argu.ToString() ment
This however, does not handle the case of (string) aFunction( obj1, obj2 ).
You may want to handle these by yourself first, or build another regexp.
I am not sure if you really want to do this as a mass conversion. As in all reality in your example, you should end up with the following.
string var1 = "1";
and
string var2 = intVar.ToString();
There is no need for your first example to be doing a cast, when it can be a string from the beginning.
Suggest you to use this one
Find: \(string\){(.*)}{:Po}
Replace: \1.ToString()\2
Good luck!
I am not too familiar with regex but I offer a warning instead. You might not want to replace all (string)xxx to xxx.toString() because (as you know I am sure) (string) is casting and a ToString() is a method call. You can only cast something as string if the object is a descendant of string. You can call ToString() if the implementor of the class overrode the ToString() method. If not then you are just going to get the default implementation.
Well, the reason that you get the extra code in the conversion, is that you don't have Option Strict On in the VB code. If you had, you wouldn't be able to do those implicit conversions in the first place.
So, the VB code should look like this, and the C# code would then look right in the conversion:
var1 As String = "1"
var2 As String = intVar.ToString
To fix this after the conversion is done is quite beyond what a regular expression is capable of. Sure, you could make an expression that would convert all (string)x to x.ToString(), but that would probably cause more problems that it fixed...

Categories

Resources