Reputation: 110
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Methods
{
class Program
{
static string firstName;
static string lastName;
static string birthday;
static void Main(string[] args)
{
GetStudentInformation();
//PrintStudentDetails(firstName, lastName,birthDay);
Console.WriteLine("{0} {1} {2}", firstName, lastName, birthday);
Console.ReadKey();
}
static void GetStudentInformation()
{
Console.WriteLine("Enter the student's first name: ");
string firstName = Console.ReadLine();
Console.WriteLine("Enter the student's last name");
string lastName = Console.ReadLine();
Console.WriteLine("Enter the student's birthday");
string birthday = Console.ReadLine();
//Console.WriteLine("{0} {1} {2}", firstName, lastName, birthDay);
}
static void PrintStudentDetails(string first, string last, string birthday)
{
Console.WriteLine("{0} {1} was born on: {2}", first, last, birthday);
}
}
}
I've tried various methods recommended to me about how to declare class variables, but every solution I get presented seems to not work. I am trying to save the input from the user into 3 variables; lastName, firstName, and birthday. Whenever you run the program it will ask for the values, and when it tries to print the variables it only shows a blank line.
How can I output my variables in this manner?
Upvotes: 2
Views: 62
Reputation: 37299
In this section:
Console.WriteLine("Enter the student's first name: ");
string firstName = Console.ReadLine();
Console.WriteLine("Enter the student's last name");
string lastName = Console.ReadLine();
Console.WriteLine("Enter the student's birthday");
string birthday = Console.ReadLine();
You are creating new variables with those names just for the scope of the method and are not assigning to those of the class. Remove the string
before them:
Console.WriteLine("Enter the student's first name: ");
firstName = Console.ReadLine();
Console.WriteLine("Enter the student's last name");
lastName = Console.ReadLine();
Console.WriteLine("Enter the student's birthday");
birthday = Console.ReadLine();
I suggest reading more into Variable and Method Scope. Also I think you should look more into the use of static classes and read: When to use static classes in C#
As Steve suggested in his answer, it is better that you create a class Student
and then populate it. However, though fits for this piece of code, I'd not declare it static
but have it returned from the function that requests the user's input.
Upvotes: 2