How does VB.NET calculate the length of a method? How can I do this in C#?
This my VB.NET code:
Private Function ZeroPad(ByRef pNumber As Integer, ByRef pLength As Integer) As String
Dim Padding As Object
If IsNumeric(pNumber) And IsNumeric(pLength) Then
Padding = New String("0", pLength)
ZeroPad = Padding & CStr(pNumber)
ZeroPad = Right(ZeroPad, pLength)
Else
ZeroPad = CStr(pNumber)
End If
End Function
I converted into C# as follows:
private string ZeroPad(ref int pNumber, ref int pLength) {
object Padding;
if ((IsNumeric(pNumber) && IsNumeric(pLength))) {
Padding = new string("0", pLength);
return (Padding + pNumber.ToString());
ZeroPad = ZeroPad.Substring((ZeroPad.Length - pLength));
// In the above line, how can I take the length of a method in C#?
}
else {
return pNumber.ToString();
}
}
You are probably confused between the variable
ZeroPadand the methodZeroPad. It is customary to write variable names with a lower case initial character, e.g.zeroPad. To return a value from a method, usereturnin C#. I’m not sure what the purpose is of yourIsNumericsubroutine or why you take value by reference, but your code in C# would be similar to:As you don’t change the values of
pNumberorpLength, you can pass them by value (ByValin Visual Basic). And knowing that bothpNumberandpLengthare integers, and therefore always numeric, your method could be shortened to the following:The .NET Framework’s Base Class Libraries have a String.PadRight method that does exactly what you want if you specify
'0'as the value forpaddingChar.