This is the class I have:
class student
{
public string Name;
public int Age;
public enum Gender
{
male,
female,
other
}
public void Write()
{
Console.WriteLine("Name: {0}, Age: {1}, ", Name, Age);
}
}
And this is the main program:
class Program
{
static void Main(string[] args)
{
student student1 = new student();
student1.Name = "Dan";
student1.Age = 15;
student1.Write();
}
}
When I run the program, the name and age variables from the main program are copied into the function Write in the class. I'm trying to do the same with the enum values - I want to write a gender variable in the main program, and add something to the fuction that will also write it, but I dont know how to do it with enum values.
If anyone can help I'd be happy to hear your suggetions.
Add a Gender Type to your class:
public enum Genders { male, female, other }
class student
{
public string Name;
public int Age;
public Genders Gender;
public void Write()
{
Console.WriteLine("Name: {0}, Age: {1}, Gender: {2}", Name, Age, Gender.ToString());
}
}
class Program
{
static void Main(string[] args)
{
student student1 = new student();
student1.Name = "Dan";
student1.Age = 15;
student1.Gender = Genders.male;
student1.Write();
}
}
Related
I'm trying to create a simple class by referring to a YouTube video, but I get errors.
Here are the errors:
And here is my code:
public class Student
{
public int stdAge;
public int stdiD;
public string stdCitizenship;
public void printStudent()
{
Console.WriteLine("Student Age: " + stdAge);
Console.WriteLine("Student ID: " + stdiD);
Console.WriteLine("Student Citizenship:" + stdCitizenship);
}
}
class Program
{
static void Main(string[] args)
{
Student std1 = new Student("Roslin Hashim");
std1.stdAge(26);
std1.stdiD(520308);
std1.stdCitizenship("Malaysia");
std1.printStudent();
}
}
How do I know what the problem is and how to fix it?
You're not setting your values properly. I assume you were trying to set stdAge, stdiD and stdCitizenship by doing the following:
std1.stdAge(26);
std1.stdiD(520308);
std1.stdCitizenship("Malaysia");
You're using them like functions when they are not. You need to put getters and setters on stdAge, stdiD and stdCitizenship and then set them using a simple = sign. You also did not create a constructor that takes in 1 string argument. So you'll need to do that. The following code should do what you're trying to do.
public class Student
{
//Setting getter and setters
public int stdAge { get; set; }
public int stdiD { get; set; }
public string stdCitizenship { get; set; }
//Here's the constructor you need
public Student(string name) {
//Code to do sometihng with name parameter here.
}
public void printStudent()
{
Console.WriteLine("Student Age: " + stdAge);
Console.WriteLine("Student ID: " + stdiD);
Console.WriteLine("Student Citizenship:" + stdCitizenship);
}
}
class Program
{
static void Main(string[] args)
{
Student std1 = new Student("Roslin Hashim");
std1.stdAge = 26;
std1.stdiD = 520308;
std1.stdCitizenship = "Malaysia";
std1.printStudent();
}
}
I have a list within my Main() and I'm trying to add an item to that list from within a variable. But it's throwing the error "The name 'dogList' does not exist in the current context"
Inside my addDog() method, dogList.Add() is not working due to above.
namespace DoggyDatabase
{
public class Program
{
public static void Main(string[] args)
{
// create the list using the Dog class
List<Dog> dogList = new List<Dog>();
// Get user input
Console.WriteLine("Dogs Name:");
string inputName = Console.ReadLine();
Console.WriteLine("Dogs Age:");
int inputAge = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Dogs Sex:");
string inputSex = Console.ReadLine();
Console.WriteLine("Dogs Breed:");
string inputBreed = Console.ReadLine();
Console.WriteLine("Dogs Colour:");
string inputColour = Console.ReadLine();
Console.WriteLine("Dogs Weight:");
int inputWeight = Convert.ToInt32(Console.ReadLine());
// add input to the list.
addDog(inputName, inputAge, inputSex, inputBreed, inputColour, inputWeight);
}
public static void addDog(string name, int age, string sex, string breed, string colour, int weight)
{
// The name 'dogList' does not exist in the current context
dogList.Add(new Dog()
{
name = name,
age = age,
sex = sex,
breed = breed,
colour = colour,
weight = weight
});
}
}
public class Dog
{
public string name { get; set; }
public int age { get; set; }
public string sex { get; set; }
public string breed { get; set; }
public string colour { get; set; }
public int weight { get; set; }
}
}
dogList is local to the method Main. What you want to do instead is to place dogList outside of that scope.
public class Program
{
static List<Dog> dogList = new List<Dog>();
...
Alternately you can send the list into your add method.
dogList exists only in the scope of the Main method. If you declare a variable in one method it becomes local and cannot be accessed in another method.
You could solve it by passing the necessary variable as a parameter:
public static void addDog(string name, int age, string sex, string breed, string colour, int weight, List<Dog> dogList)
now you pass the variable in the call like this:
// add input to the list.
addDog(inputName, inputAge, inputSex, inputBreed, inputColour, inputWeight, dogList);
or you can declare the variable at the scope of the class:
public class Program
{
// create the list using the Dog class
static List<Dog> dogList = new List<Dog>();
In the latter version you need to declare it as static, otherwise the compiler will demand an Instance of the class Program to be able to access the variable
The dogList variable is scoped local to the Main method, so it is not accessible to other method in your class, you have few ways to make it correct, one solution can be to pass the dogList as well as parameter to that method like:
// add input to the list.
addDog(inputName, inputAge, inputSex, inputBreed, inputColour, inputWeight,dogList);
and change the signature of addDog method as well to be :
public static void addDog(string name, int age, string sex, string breed, string colour, int weight, List < Dog > dogList)
{
}
If you don't want to do that way, another solution can be to make your dogList variable at class level i.e. make it field like:
public class Program
{
List<Dog> dogList = new List<Dog>();
}
The main problem is that you have declared dogList locally from within main. You have also declared addDog as static. Static methods are outside of the current object.
Think of Main as your living room you are standing in your living room. Now think of addDog as your bathroom I am standing in there. We have know knowledge that each other is there so there is no way of us to communicate.
public class DogDb
{
// DogDb contains a list of dogs
public List<Dog> dogs { get; set; }
public DogDb() {
dogs = new List<Dog>();
}
// DogDb can control adding new dogs to its list of dogs.
public void addDog(string name, int age, string sex, string breed, string colour, int weight)
{
dogs.Add(new Dog()
{
name = name,
age = age,
sex = sex,
breed = breed,
colour = colour,
weight = weight
});
}
public class Dog
{
public string name { get; set; }
public int age { get; set; }
public string sex { get; set; }
public string breed { get; set; }
public string colour { get; set; }
public int weight { get; set; }
}
}
public class Program
{
public static void Main(string[] args)
{
// Create a new instance of our DogDB class.
var DogDb = new DogDb();
// Get user input
Console.WriteLine("Dogs Name:");
string inputName = Console.ReadLine();
Console.WriteLine("Dogs Age:");
int inputAge = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Dogs Sex:");
string inputSex = Console.ReadLine();
Console.WriteLine("Dogs Breed:");
string inputBreed = Console.ReadLine();
Console.WriteLine("Dogs Colour:");
string inputColour = Console.ReadLine();
Console.WriteLine("Dogs Weight:");
int inputWeight = Convert.ToInt32(Console.ReadLine());
// add input to the object.
DogDb.addDog(inputName, inputAge, inputSex, inputBreed, inputColour, inputWeight);
}
#Ari....Here is how you can do it
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication4
{
namespace DoggyDatabase
{
public class Program
{
private static List<Dog> dogList = new List<Dog>();
public static void Main(string[] args)
{
// create the list using the Dog class
// Get user input
Console.WriteLine("Dogs Name:");
string inputName = Console.ReadLine();
Console.WriteLine("Dogs Age:");
int inputAge = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Dogs Sex:");
string inputSex = Console.ReadLine();
Console.WriteLine("Dogs Breed:");
string inputBreed = Console.ReadLine();
Console.WriteLine("Dogs Colour:");
string inputColour = Console.ReadLine();
Console.WriteLine("Dogs Weight:");
int inputWeight = Convert.ToInt32(Console.ReadLine());
// add input to the list.
addDog(inputName, inputAge, inputSex, inputBreed, inputColour, inputWeight);
}
public static void addDog(string name, int age, string sex, string breed, string colour, int weight)
{
// The name 'dogList' does not exist in the current context
dogList.Add(new Dog()
{
name = name,
age = age,
sex = sex,
breed = breed,
colour = colour,
weight = weight
});
}
}
public class Dog
{
public string name { get; set; }
public int age { get; set; }
public string sex { get; set; }
public string breed { get; set; }
public string colour { get; set; }
public int weight { get; set; }
}
}
}
The list was inaccessible due to its protection level.When you have to use a list in another method then you have to declare it first.Happy coding
I have 3 classes (UCourse, Student and Teacher) and each class has a unique string property.
Is there a simple way I can take the string property from the first class UCourse, pass it into a 2nd class Student, and then pass that string plus another string from the 2nd class into a 3rd class Teacher?
This is what I have so far for my 3 classes:
using System;
namespace EDXonline_AssignmentFour
{
class Program
{
class UCourse
{
// Set the unique string for the 1st class
private string course = "Computer Scienece";
public string Course
{
get { return course; }
}
}
class Student
{
// Get the string from the 1st class
UCourse ucourse = new UCourse();
public string coursef1
{
get { return ucourse.Course; }
}
// Set the unique string for the 2nd class
private string name = "zach";
public string Name
{
get { return name; }
}
}
class Teacher
{
Student student = new Student();
private string namet = "Sally";
// Get the unique string from the 2nd class
public string namef1
{
get { return student.Name; }
}
// Set the unique string for the 3rd class
public string Namet
{
get { return namet; }
}
}
}
}
Then, I need to create an instance of Teacher and by using only this instance of Teacher, I need to output all string properties from each of the 3 classes like this:
public static void Main (string [] args)
{
Teacher teacher = new Teacher();
Console.WriteLine("{0} and {1} are in {2}",
teacher.namef1, teacher.Namet /*, UCourse string from the 1st class goes here*/);
}
So far that works to display the strings from the 2nd and 3rd classes, but how can I get the value of the UCourse string from the first class as well?
If you want to use your existing code and keep passing the strings through properties, then you almost solved it because your Main() method already shows the correct values of the strings from the 2nd and 3rd classes.
To access the string from the 1st class and use it in the 3rd class, you can add another property to the 3rd class to get it (same as you already did to get the string from the 2nd class).
For example:
class Teacher
{
Student student = new Student();
// Get the unique string from the 2nd class
public string namef1
{
get { return student.Name; }
}
// Get the unique string from the 1st class that's already stored in the 2nd class
public string UCourseName
{
get { return student.coursef1; }
}
// Set the string for the third class
private string namet = "Sally";
public string Namet
{
get { return namet; }
}
}
And then you can update your Main() method to use it like this:
public static void Main(string[] args)
{
Teacher teacher = new Teacher();
// Writes "Zach and Sally are in Computer Science"
Console.WriteLine("{0} and {1} are in {2}",
teacher.namef1, teacher.Namet, teacher.UCourseName);
Console.ReadLine();
}
that would be :
internal class Program
{
private static void Main( string[] args )
{
Teacher teacher = new Teacher();
Console.WriteLine("{0} and {1} are in {2}",
teacher.Namef1, teacher.Namet, teacher.Course);
}
private class UCourse
{
// Set the unique string for the 1st class
private readonly string course = "Computer Scienece";
public string Course { get { return this.course; } }
}
private class Student
{
// Set the unique string for the 2nd class
private readonly string _name = "zach";
public string Name { get { return this._name; } }
// Get the string from the 1st class
private readonly UCourse _ucourse = new UCourse( );
public string Coursef1 { get { return this._ucourse.Course; } }
}
private class Teacher
{
private readonly Student _student = new Student( );
// Get the unique string from the 1nd class
public string Course { get { return this._student.Coursef1; } }
// Get the unique string from the 2nd class
public string Namef1 { get { return this._student.Name; } }
// Set the unique string for the 3rd class
private readonly string _namet = "Sally";
public string Namet { get { return this._namet; } }
}
}
I recommend that you rethink your classes. Here is a small example:
using System;
using System.Collections.Generic;
namespace Example
{
public class Course
{
public string CourseTitle { get; set; }
public List<Student> Students { get; set; }
public Course(string courseTitle)
{
CourseTitle = courseTitle;
Students = new List<Student>();
}
}
public class Student
{
public string Name { get; set; }
public Student(string name)
{
Name = name;
}
}
public class Teacher
{
public string Name { get; set; }
public List<Course> Courses { get; set; }
public Teacher(string name)
{
Name = name;
Courses = new List<Course>();
}
}
class Program
{
static void Main(string[] args)
{
List<Teacher> teachers = new List<Teacher>();
Course course1 = new Course("Astrophysics A");
Course course2 = new Course("Coding C#");
Student student1 = new Student("Peter");
Student student2 = new Student("Bill");
Student student3 = new Student("Anna");
Teacher teacher1 = new Teacher("Mr. Williams");
Teacher teacher2 = new Teacher("Mr. Jacobson");
course1.Students.Add(student1);
course1.Students.Add(student3);
course2.Students.Add(student2);
teacher1.Courses.Add(course1);
teacher2.Courses.Add(course2);
teachers.Add(teacher1);
teachers.Add(teacher2);
foreach (Teacher teacher in teachers)
{
foreach (Course course in teacher.Courses)
{
foreach (Student student in course.Students)
{
Console.WriteLine("{0} and {1} are in {2}", student.Name, teacher.Name, course.CourseTitle);
}
}
}
Console.ReadLine();
}
}
}
I guess this way provides you more flexibility, in your code only 1 to 1 connections are possible.
Hope this was helpful.
I learning C#. I want to see what is the best way to implement inheritance. I have a Employee base class and a PartTime derived class. Employee class only receives First and Last name and has a method to print full name.
I want to know what is the proper way to pass First and last name so that when I just call PartTime class I should be also able to print full name from the calling program. At the moment it is showing blank as full name:
class Program
{
static void Main(string[] args)
{
Employee emp = new Employee("John", "Doe");
// emp.PrintFullName();
PartTime pt = new PartTime();
float pay=pt.CalcPay(10, 8);
pt.PrintFullName();
Console.WriteLine("Pay {0}", pay);
Console.ReadKey();
}
}
public class Employee
{
string _firstName;
string _last_name;
public Employee(string FName, string LName)
{
_firstName = FName;
_last_name = LName;
}
public Employee() { }
public void PrintFullName()
{
Console.WriteLine("Full Name {0} {1} ", _firstName, _last_name);
}
}
public class PartTime : Employee
{
public float CalcPay(int hours, int rate)
{
return hours * rate;
}
}
You can call the base class constructor from you derived class like this:
public class PartTime : Employee
{
public PartTime(string FName, string Lname)
: base(FName, LName)
{ }
}
and then create it,
PartTime pt = new PartTime("Part", "Time");
Try this:
public class Employee
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Employee(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
}
//method implementations removed for clarity
}
public class PartTime:Employee
{
public PartTime(string firstName, string lastName)
: base(firstName, lastName)
{
}
}
Note that your base constructor will run before any code in your derived constructor, should you need further initialization logic in the PartTime class.
You want to add a constructor to PartTime that will pass along the first and last name to the base constructor
public PartTime(string fName, string lName) : base(fName, lName) {
}
Or you could make first and last name public properties on Employee which would be inherited by PartTime. Then you can initialize them when creating instances of either without having to maintain the PartTime constructor.
class Program
{
static void Main(string[] args)
{
Employee emp = new Employee { FirstName = "John", LastName = "Doe" };
emp.PrintFullName();
PartTime pt = new PartTime { FirstName = "Jane", LastName = "Doe" };
float pay=pt.CalcPay(10, 8);
pt.PrintFullName();
Console.WriteLine("Pay {0}", pay);
Console.ReadKey();
}
}
public class Employee
{
public string FirstName { get; set; }
public string LastName { get; set; }
public void PrintFullName()
{
Console.WriteLine("Full Name {0} {1} ", FirstName, LastName);
}
}
public class PartTime : Employee
{
public float CalcPay(int hours, int rate)
{
return hours * rate;
}
}
So basically my issue is that I have a method in my program that sets the data in a struct for a student which looks like:
public static void addingstudent(){
student student;
AddStudent details = new AddStudent();
student.name = details.setName();
student.course = details.setCourse();
student.studentno = details.setStudentNumber();
student.year = details.setYear();
menu();
}
The AddStudent class contains a few methods for asking the user to input the Name etc. and returning them, an example in this class would be:
public static int setStudentNo(){
Console.Write("Please enter Student Number: ");
int StudentNo = int.Parse(Console.ReadLine());
return StudentNo;
}
And then I'm trying to access that data and display it on screen with:
public static void getstudent(){
student student;
student.displayDetails();
}
Which is just displaying null values for all the variables, however if I call this after first setting the values it displays correctly, lastly the struct looks like:
public struct student{
public String name;
public int studentno;
public String course;
public int year;
public void displayDetails(){
Console.WriteLine("Name: " + name);
Console.WriteLine("Student Number: "+studentno);
Console.WriteLine("Course: "+course);
Console.WriteLine("Year: "+year);
}
You user student student in addingstudent() but another student student in getstudent() as far as I can see... you are not using the same object...
You can have a class which has the struct and the two functions
class A
{
studnet studnet;
public static void addingstudent()
{
AddStudent details = new AddStudent();
student.name = details.setName();
student.course = details.setCourse();
student.studentno = details.setStudentNumber();
student.year = details.setYear();
menu();
}
public static void getstudent()
{
student.displayDetails();
}
}
Then just create a new A class and manipulate with the data however you want
Creating mutable structs is a bad idea in the first place, if the data is mutable you really should create a class.
Also, you are not passing the stuct as a parameter, for example in getstudent you are creating a new student object every time, this is why student.displayDetails(); is showing null, because you have not set any of the properties of the student you created on the line before you call it.
public static void getstudent()
{
Student student; // creates a new instance of the struct...
student.displayDetails(); // obviously student properties are null...
}
Really you should be doing something like the following.
public class Student
{
public Student()
{
this.SetName();
this.SetNumber();
this.SetCourse()
this.SetYear();
}
public override string ToString()
{
return string.Format(
"Name: {0}{4}Number: {1}{4}Course: {2}{4}Year: {3}{4}",
this.Name,
this.Number,
this.Course,
this.Year,
Environment.NewLine);
}
public void DisplayDetails()
{
Console.WriteLine(this.ToString());
}
public string Name { get; private set; }
public string Number{ get; private set; }
public string Course { get; private set; }
public string Year { get; private set; }
public static void SetName()
{
Console.WriteLine("Please enter Name: ");
this.Name = Console.ReadLine();
}
public static void SetNumber()
{
Console.WriteLine("Please enter Number: ");
this.Number = int.Parse(Console.ReadLine());
}
public static void SetCourse()
{
Console.WriteLine("Please enter Course: ");
this.Course = Console.ReadLine();
}
public static void SetYear()
{
Console.WriteLine("Please enter Year: ");
this.Year = int.Parse(Console.ReadLine());
}
}
public class App
{
public static void Main()
{
Student student1 = new Student(); // Create a student
student1.DisplayDetails(); // show the details
student1.SetName(); // change the name
student1.SetYear(); // change the year
student1.DisplayDetails(); // show the new details
// etc...
}
}