user1794624
user1794624

Reputation: 83

I can't print a variable on console

I am learning C# and I wrote below code but I am unable to print the name on console. Can any one tell me why?

 public class BaseClass
{
    public String Name;

    public void Print()
    {

        Console.WriteLine("Name is:", Name);

    }

}
class PublicDemo
{
    static void Main(string[] args)
    {
        BaseClass bc = new BaseClass();
        Console.Write("Enter your Name:");
        bc.Name = Console.ReadLine();
        Console.ReadLine();
        bc.Print();
        Console.ReadLine();
    }
}

Upvotes: 0

Views: 6531

Answers (3)

dav_i
dav_i

Reputation: 28147

It's because you don't have a format parameter in your WriteLine call:

Console.WriteLine("Name is:{0}", Name);
// Name is:user1794624

You can do lots:

Console.WriteLine("Name three times: {0} {0} {0}, followed by three {1}", Name, 3);
// Name three times: user1794624 user1794624 user1794624, followed by three 3

Upvotes: 6

Alberto Solano
Alberto Solano

Reputation: 8227

The line Console.Write("Enter your Name:"); is the problem. It will never print the value or your variable Name, because you didn't included it in the overload of Console.Write.

The Console.Write Method (String, Object[]) has the same behavior of the method String.Format. Indeed the line Console.Write("Enter your Name: {0}", Name); has the same output of

Console.Write(String.Format("Enter your Name: {0}",Name));

Use then:

Console.Write("Enter your Name: {0}", Name);

or

Console.Write("Enter your Name: " + Name);

or

Console.Write(String.Format("Enter your Name: {0}",Name));

Upvotes: 2

Mohamad Shiralizadeh
Mohamad Shiralizadeh

Reputation: 8765

try this:

Console.WriteLine("Name is: {0}", Name);

Console.Write Method (String, Object[]) works like String.Format.

This method uses the composite formatting feature of the .NET Framework to convert the value of an object to its text representation and embed that representation in a string. The resulting string is written to the output stream.

The format parameter consists of zero or more runs of text intermixed with zero or more indexed placeholders, called format items, that correspond to an object in the parameter list of this method. The formatting process replaces each format item with the text representation of the value of the corresponding object.

The syntax of a format item is {index[,alignment][:formatString]}, which specifies a mandatory index, the optional length and alignment of the formatted text, and an optional string of format specifier characters that govern how the value of the corresponding object is formatted.

Console.Write MSDN

String.Format MSDN

Upvotes: 4

Related Questions