Reputation: 475
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?
Upvotes: 19
Views: 118469
Reputation: 41
you can use something like this
long count = 12345;
string s = long.Parse(count, CultureInfo.InvariantCulture);
or simply
string s = count.ToStringInvariant();
textBox1.Text = s;
Upvotes: 0
Reputation: 6524
There are different ways to convert long to string.
Using .ToString()
long testField = 100; string stringEquivalent = testField.ToString();
Using string.Format
long testField = 123; string stringEquivalent = string.Format("{0}", testField);
Using Convert.ToString
long testField = 123; string stringEquivalent = Convert.ToString(testField);
Using String interpolation
long testField = 123; string stringEquivalent = $"{testField}";
Using + operator
long testField = 123; string stringEquivalent = "" + testField;
Using StringBuilder
long testField = 123; string stringEquivalent = new StringBuilder().Append(testField).ToString();
Using TypeConverter
TypeConverter converter = TypeDescriptor.GetConverter(typeof(long)); long testField = 123; string stringEquivalent = (string)converter.ConvertTo(testField, typeof(string));
Upvotes: 1
Reputation: 124
champs.
I did this: "Cast the dynamic value to long and convert to string"
((long)x.PersonId).ToString();
Upvotes: -1
Reputation: 4327
try this textBox1.Text = CountLinesInFile("test.txt").ToString();
Upvotes: 0
Reputation: 17395
Use the ToString()
method like this:
textBox1.Text = CountLinesInFile("test.txt").ToString();
Upvotes: 37
Reputation: 136124
In Java its a simply .ToString
And in C#, its simply .ToString()
.
Happy learning.
Upvotes: 12
Reputation: 176906
just write
textBox1.Text =(CountLinesInFile("test.txt")).ToString();
MSDN: Object.ToString Method - Returns a string that represents the current object.
Upvotes: 5