Code Beast
Code Beast

Reputation: 475

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?

Upvotes: 19

Views: 118469

Answers (7)

dmitryaivanov
dmitryaivanov

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

Gauravsa
Gauravsa

Reputation: 6524

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

Upvotes: 1

CelzioBR
CelzioBR

Reputation: 124

champs.

I did this: "Cast the dynamic value to long and convert to string"

((long)x.PersonId).ToString();

Upvotes: -1

JohnnBlade
JohnnBlade

Reputation: 4327

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

Upvotes: 0

Blachshma
Blachshma

Reputation: 17395

Use the ToString() method like this:

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

Upvotes: 37

Jamiec
Jamiec

Reputation: 136124

In Java its a simply .ToString

And in C#, its simply .ToString().

Happy learning.

Upvotes: 12

Pranay Rana
Pranay Rana

Reputation: 176906

just write

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

MSDN: Object.ToString Method - Returns a string that represents the current object.

Upvotes: 5

Related Questions