C# Convert a Long to String
Here My Problem Is: I Have This Code: Static Long Countlinesinfile(String F) { Long Count = 0; Using (Streamreader R = New Streamreader(F)) { String Line...
Here my problem is:
I have this code:
static long CountLinesInFile(string f)
{
long count = 0;
using (StreamReader r = new StreamReader(f))
{
string line;
while ((line = r.ReadLine()) != null)
{
count++;
}
}
return count;
}
Which counts the lines of a text file. The problem I have is that when I'm trying this:
textBox1.Text = CountLinesInFile("test.txt");
I'm getting an error:
Error 1 Cannot implicitly convert type 'long' to 'string'
It seems legit, but how am I supposed to convert it to string? In Java its a simple toString()
Can someone give me a solution?
6 Answers
Use the ToString() method like this:
textBox1.Text = CountLinesInFile("test.txt").ToString();
In Java its a simply .ToString
And in C#, its simply .ToString().
Happy learning.
just write
textBox1.Text =(CountLinesInFile("test.txt")).ToString();
MSDN: Object.ToString Method - Returns a string that represents the current object.
try this textBox1.Text = CountLinesInFile("test.txt").ToString();
champs.
I did this: "Cast the dynamic value to long and convert to string"
((long)x.PersonId).ToString();
There are different ways to convert long to string.
Using
.ToString()long testField = 100; string stringEquivalent = testField.ToString();
Using
string.Formatlong testField = 123; string stringEquivalent = string.Format("{0}", testField);
Using
Convert.ToStringlong testField = 123; string stringEquivalent = Convert.ToString(testField);
Using
String interpolationlong testField = 123; string stringEquivalent = $"{testField}";
Using + operator
long testField = 123; string stringEquivalent = "" + testField;
Using
StringBuilderlong testField = 123; string stringEquivalent = new StringBuilder().Append(testField).ToString();
Using
TypeConverterTypeConverter converter = TypeDescriptor.GetConverter(typeof(long)); long testField = 123; string stringEquivalent = (string)converter.ConvertTo(testField, typeof(string));