C# Convert a Long to String

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;
        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?

2

6 Answers

Use the ToString() method like this:

textBox1.Text = CountLinesInFile("test.txt").ToString();
1

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();
2

There are different ways to convert long to string.

  1. Using .ToString()

    long testField = 100; string stringEquivalent = testField.ToString();

  2. Using string.Format

    long testField = 123; string stringEquivalent = string.Format("{0}", testField);

  3. Using Convert.ToString

    long testField = 123; string stringEquivalent = Convert.ToString(testField);

  4. Using String interpolation

    long testField = 123; string stringEquivalent = $"{testField}";

  5. Using + operator

    long testField = 123; string stringEquivalent = "" + testField;

  6. Using StringBuilder

    long testField = 123; string stringEquivalent = new StringBuilder().Append(testField).ToString();

  7. Using TypeConverter

    TypeConverter converter = TypeDescriptor.GetConverter(typeof(long)); long testField = 123; string stringEquivalent = (string)converter.ConvertTo(testField, typeof(string));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins
Author

Sarah Jenkins

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.