Hi am new to OOP and I am doing a task right now however I cant link the customer class and objects into my main program. It says that it doesn't exist in the current context. This maybe also due to me not understanding the name spaces completely and may have the names of the class in the file directory being incorrect but if I am honest I don't know.
Main program (file direct name is MainProg)
class Program
{
static void Main(string[] args)
{
//New Customer Account Sequence
//Customer customerOne = new Customer();
Console.WriteLine("Customer Details:\n-----------------\n");
Console.Write("Please enter cutomer forename: ");
customerOne.Forename = Console.ReadLine();
customerOne.Surname = Console.ReadLine();
customerOne.Address = Console.ReadLine();
customerOne.Town = Console.ReadLine();
customerOne.Postcode = Console.ReadLine();
CurrentAccount accountCurrOne = new CurrentAccount();
//accountCurrOne.AccountNumber = 1000;
SavingsAccount accountSavOne = new SavingsAccount();
accountSavOne.AccountNumber = 1001;
accountCurrOne.Open(customerOne);
accountSavOne.Open(customerOne);
//Initial deposit
decimal depositAmount;
depositAmount = decimal.Parse(Utility.Console.Ask("Enter initial deposit: "));
accountCurrOne.Deposit(depositAmount);
accountSavOne.Deposit(depositAmount);
// End of New Customer Account Sequence
Console.ReadLine();
}
}
Customer Class (Name in file directory is CustomerOne)
class CustomerOne : BankAccount
{
protected string _Forename;
protected string _Surname;
protected string _Address;
protected string _Town;
protected string _Postcode;
public string Forename
{
get { return _Forename; }
set { Forename = value; }
}
public string Surname
{
get { return _Surname; }
set { Surname = value; }
}
public string Address
{
get { return _Address; }
set { Address = value; }
}
public string Town
{
get { return _Town; }
set { Town = value; }
}
public string Postcode
{
get { return _Postcode; }
set { Postcode = value; }
}
}
Can someone tell me where I am messing up?
In order to call properties and methods of an object, you must instantiate it.
The problem is the following line that you commented:
//Customer customerOne = new Customer();
This line creates a new instance of the Customer class. Once you create an instance with the keyword new and assigned it to a variable, you can call class methods and properties with variable.Property or variable.Method().
This applies for classes that are not Static.
A reference for instances: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/objects
Related
Im writing a code where you can search a name and the subjects teaches will pop-up etc..
however I'm not really sure why but i'm getting Object reference not set to an instance of an object error im missing something i know, can someone help me? i tried different methods didn't really work... heres my code :
public partial class MainWindow : Window
{
Course my = new Course();
public class Course
{
public string[] Name { get; set; }
public string[] Subject { get; set; }
public string[] Hour { get; set; }
public Course(string[] name, string[] subject, string[] hour)
{
this.Name = name;
this.Subject = subject;
this.Hour = hour;
}
}
public MainWindow()
{
InitializeComponent();
my.Name[0] = "Ali";
my.Name[1] = "Sefer";
my.Subject[0] = "INFORMATIKA";
my.Subject[1] = "ENGLISH";
my.Hour[0] = "12";
my.Hour[1] = "22";
}
private void searchButton_Click(object sender, RoutedEventArgs e)
{
Find();
}
private void Find()
{
int index = 0;
string wanted = wantedName.Text;
while (my.Name[index] != wanted && (my.Name[index] != "END"))
{
index++;
}
if (my.Name[index] == wanted)
{
outputLabel.Content = " " + my.Name[index] + " " + my.Subject[index];
}
else
{
outputLabel.Content = "Name not found";
}
}
}
}
You are using arrays without initializing them. While you have defined a constructor for your Course class that takes values for the arrays, you are using the default constructor. Try calling your own constructor with arguments like
Course my = new Course(new string[2], new string[2], new string[2]);
Before you can assign a value to an element like my.Name[0], you have to ensure that my.Name is referencing an allocated array, which means there is memory available for your elements.
I'm trying to return multiple parameters, if that's how to word it. I'm trying to "translate" Python code into C#.
I'm actually not quite sure what exact term I'm searching for, but I know how to do it in Python so I'll just show my code.
class Staff
{
public String name;
public int age;
/* Now in Python, you can easily write this following, but I have no
idea how this works in C#. I basically want to return all the values
for each employee in the "Staff" class */
def desc(self):
desc_str = "%s is %s years old." % (self.name, self.age)
return desc_str
}
class Program
{
public static void Main()
{
Staff Jack = new Staff();
Jack.name = "Jack";
Jack.age = 40;
Staff Jill = new Staff();
Jill.name = "Jill";
Jill.age = 50;
Console.WriteLine(Jack.desc());
Console.WriteLine(Jill.desc());
Console.ReadKey();
}
}
EDIT: I figured out that what I was searching for was get, set and ToString() and will look into it now.
The code I've translated looks like the following now:
class Staff
{
private string name;
private int age;
private string yearsold = " years old.";
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public int Age
{
get
{
return age;
}
set
{
age = value;
}
}
public string YearsOld
{
get
{
return yearsold;
}
set
{
yearsold = value;
}
}
public override string ToString()
{
return "Employee " + Name + " is " + Age + YearsOld;
}
}
class TestPerson
{
static void Main()
{
// Create a new Person object:
Staff person = new Staff();
person.Name = "Jack";
person.Age = 40;
Console.WriteLine(person);
person.Name = "Jill";
person.Age = 50;
Console.WriteLine(person);
Console.ReadKey();
}
}
Since you have a class, you can override the ToString function and use the string.Format function like so:
class Staff
{
public string name;
public int age;
public Staff(string _name, int _age)
{
this.name = _name;
this.age = _age;
}
public override string ToString()
{
return string.Format("{0} is {1} years old.", this.name, this.age);
}
}
Then to print:
Staff Jack = new Staff("Jack", 40);
Console.WriteLine(Jack); // implicitly calls Jack.ToString()
Hope that helps.
Forgive a stupid question but I am new to C# & OOP.
Can anyone help me prevent a “System.NullReferenceException:”?
I’m trying to do an assignment following instructions and using what we’ve learned to date (arrays, classes and constructors).
I’ve created an array of StudentSubjects classes and embedded this in an array of Student classes.
I want to print out details of each student’s subjects.
I can access the StudentArray[0] fields OK but can’t get to the StudentArray[0].StudentSubjectsArray[0] fields because "Object reference not set to an instance of an object”
I’ve spent 2 weeks looking for an answer but cannot find any examples of how to set
StudentArray[0].StudentSubjectsArray[0].SubjectName = "Algebra";
Any advice most appreciated. My code is below ....
using System;
namespace Nested_Arrays
{
public class Program
{
static void Main(string[] args)
{
Student[] StudentArray = new Student[1];
Console.WriteLine($"Hello");
StudentArray[0] = new Student();
StudentArray[0].StudentName = "Peter";
StudentArray[0].StudentLocation = "Australia";
Console.WriteLine($"{StudentArray[0].StudentName,10} {StudentArray[0].StudentLocation,15}");
StudentArray[0].StudentSubjectsArray[0].SubjectName = "Algebra";
StudentArray[0].StudentSubjectsArray[0].StudentsResult = "Pass";
Console.WriteLine($"{StudentArray[0].StudentName,10} {StudentArray[0].StudentLocation,15} {StudentArray[0].StudentSubjectsArray[0].SubjectName,15} {StudentArray[0].StudentSubjectsArray[0].StudentsResult,10}");
Console.WriteLine($"Goodbye");
}
public class Student
{
public string StudentName;
private string studentName
{ get { return studentName; } set { studentName = value; } }
public string StudentLocation;
private string studentLocation
{ get { return studentLocation; } set { studentLocation = value; } }
public StudentSubjects[] StudentSubjectsArray;
private StudentSubjects[] studentSubjectsArray
{ get { return studentSubjectsArray; } set { studentSubjectsArray = value; } }
//Constructor
public Student() { }
}
public class StudentSubjects
{
public string SubjectName;
private string subjectName
{ get { return subjectName; } set { subjectName = value; } }
public string StudentsResult;
private string studentsResult
{ get { return studentsResult; } set { studentsResult = value; } }
//Constructor
public StudentSubjects() { }
}
}
}
You just need to add the following:
StudentArray[0].StudentSubjectsArray = new StudentSubjects[1];
StudentArray[0].StudentSubjectsArray[0] = new StudentSubjects();
// and only then
StudentArray[0].StudentSubjectsArray[0].SubjectName = "Algebra";
In my opinion, a good practice is to initialize arrays in the constructor. In this way you are sure it is not null when using the object.
So do something like:
//Constructor
public Student() {
this.studentSubjectsArray = new StudentSubjects[1];
}
As others have said, you need to create the arrays before you assign objects in the array, although you can do both at the same time.
For example, if you want to do it all in one line, this would work:
Student[] StudentArray = {
new Student {
StudentName = "Peter",
StudentLocation = "Australia",
StudentSubjectsArray = new[] {
new StudentSubjects {
SubjectName = "Algebra",
StudentsResult = "Pass"
}
}
}
};
I get an error when run the console app since obviously instance of P doesnt exist. What I cant understand is where should be "newing" it? Should it be in the constructor of Employee (that didnt work when I tried) ??
public class Person
{
private string name;
public string Name // read-write instance property
{
get
{
return name;
}
set
{
name = value;
}
}
}
interface IEmployee
{
Person P
{
get;
set;
}
int Counter
{
get;
}
}
public class Employee : IEmployee
{
private Person p;
public static int numberOfEmployees;
public Person P // read-write instance property
{
get
{
return p;
}
set
{
p = value;
}
}
private int counter;
public int Counter // read-only instance property
{
get
{
return counter;
}
}
public Employee() // constructor
{
counter = ++counter + numberOfEmployees;
}
}
class Program
{
static void Main(string[] args)
{
System.Console.Write("Enter number of employees: ");
Employee.numberOfEmployees = int.Parse(System.Console.ReadLine());
Employee e1 = new Employee();
System.Console.Write("Enter the name of the new employee: ");
e1.P.Name = System.Console.ReadLine();
System.Console.WriteLine("The employee information:");
System.Console.WriteLine("Employee number: {0}", e1.Counter);
System.Console.WriteLine("Employee name: {0}", e1.P.Name);
Console.ReadLine();
}
}
Yes, somewhere in your program you are missing the line
e1.P = new Person();
Either right in front of reading the name, or maybe in the constructor of Employee.
If you modify your code like this, it will work
class Program
{
static void Main(string[] args)
{
System.Console.Write("Enter number of employees: ");
Employee.numberOfEmployees = int.Parse(System.Console.ReadLine());
Employee e1 = new Employee();
e.P = new Person(); //add this line
System.Console.Write("Enter the name of the new employee: ");
e1.P.Name = System.Console.ReadLine();
System.Console.WriteLine("The employee information:");
System.Console.WriteLine("Employee number: {0}", e1.Counter);
System.Console.WriteLine("Employee name: {0}", e1.P.Name);
Console.ReadLine();
}
}
In my program I have a list of marks and a dictionary which stores the studentId. I want that the user enters the studentId and according to that id it will point to the list of marks. I think I am implementing it incorrectly. Can someone help me in implementing it. Thanks
public class Student() {
private string name;
private string surname;
private string dob;
private string address;
private int id;
public Student()
{
}
public Student(string year,string name, string surname, string dob, string address)
{
this.name = name;
this.surname = surname;
this.dob = dob;
this.address = address;
this.year = year;
}
public string Name
{
get { return name; }
set { name = value; }
}
public string Surname
{
get { return surname; }
set { surname = value; }
}
public string DOB
{
get { return dob; }
set { dob = value; }
}
public string Addr
{
get { return address; }
set { address = value; }
}
public int Id
{
get { return id; }
set { id = value; }
}
private string year;
public string Year
{
get { return year; }
set { year = value; }
}
public Student(string s)
{
string[] splitted = s.Split(',');
name = splitted[0];
surname = splitted[1];
dob = splitted[2];
address = splitted[3];
// id = splitted[4];
}
public Dictionary<int,List<Marks>> dictionary= new Dictionary<int,List<Marks>>();
public List<Marks> Mathematics = new List<Marks>();
public List<Marks> English = new List<Marks>();
public List<Marks> Maltese = new List<Marks>();
public List<Marks> ReligiousStudies = new List<Marks>();
public List<Marks> SocialStudies = new List<Marks>();
public Dictionary<int, List<Marks>> dictionar = new Dictionary<int, List<Marks>>();
public void AddMarks(int hyexam, int anexam)
{
{
Console.WriteLine("enter id of student to input marks to:");
string id = Console.ReadLine();
if (dictionar.ContainsKey(Id).Equals(id))
{
Mathematics.Add(new Marks(hyexam, anexam));
English.Add(new Marks(hyexam, anexam));
Maltese.Add(new Marks(hyexam, anexam));
ReligiousStudies.Add(new Marks(hyexam, anexam));
SocialStudies.Add(new Marks(hyexam, anexam));
dictionar.Add(id, (Mathematics)); //dont know how to implement it
}
else
{
Console.WriteLine("id not found");
}
}
}
public class Marks
{
private int hyexam;
private int anexam;
private string id;
public int HYEXAM
{
get { return hyexam; }
set { hyexam = value; }
}
public int ANEXAM
{
get { return anexam; }
set { anexam = value; }
}
public string Id
{
get { return id; }
set { id = value; }
}
public Marks(int hyexam, int anexam)
{
this.hyexam = hyexam;
this.anexam = anexam;
}
public Marks(string id)
{
this.id = id;
}
public double OverallExam()
{
return (0.4 * hyexam) + (0.6 * anexam);
}
}
}
I'd say the main problem is your modelling. You've included the Dictionary<int, List<Marks>> as a field within Student. That means that each Student object has a dictionary. That makes no sense - because the key for the dictionary is meant to be the student ID, right?
It probably makes sense for each Student object to the lists of marks as you've currently got (although not as public fields, IMO). Given that information, do you really need a Dictionary going to the marks at all? Wouldn't it be cleaner to have a Dictionary<int, Student> somewhere (not in the Student class - maybe in a School class?) mapping each student ID to a Student, and you can get the marks from the Student?
Think hard about what you're trying to achieve, and where the data really belongs. In my experience, when you've got the data modelling right, the code usually follows in a clean way.
(I'd also question your Marks class, both in terms of name and design. What are those properties meant to represent? Isn't it really a single mark in an exam? Perhaps ExamResult would be clearer? Does it really need to be mutable?)
I'd agree with Jon that this is definitely a modeling issue (based on the OP's other posts). If you're new to object oriented programming, the first thing you need to do is determine what objects you'll need to create to answer the problem.
What is a Student? A student has a name, id, dob, class year, etc. For every attribute a student has, you need to set up a field or property.
public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public DateTime DoB { get; set; }
... etc ...
}
What is a Mark? From your descriptions, a Mark has a subject, a mid-exam score, and an annual-exam score.
public class Mark
{
public string Subject { get; set; }
public int MidScore { get; set; }
public int FinalScore { get; set; }
}
What is the relationship between a Student and a Mark? A student has a list of marks associated with them. This is best described with a List<> object.
public class Student() // continued
{
public List<Mark> Marks { get; set; }
}
Once you have the basics set up for your objects, it will be easier to filter out what you DON'T need, and make it much easier to answer your question. :)
My proposal:
Your "Mark" class must have something that identifies the subject (could be an enum called Subject, or an string, or an int with the ID of the subject if you have it stored in database)
Then you could have:
Console.WriteLine("enter id of student to input marks to:");
string id = Console.ReadLine();
var marks = new Dictionary<int, List<Mark>>();
if (UserExists(id))
{
Console.WriteLine("mark for subject1:");
string s1 = Console.ReadLine();
Console.WriteLine("mark for subject2:");
string s2 = Console.ReadLine();
var list = new List<Mark>();
list.Add(new Mark { Subject = SubjectEnum.Subject1, Value = Convert.ToDecimal(s1), });
list.Add(new Mark { Subject = SubjectEnum.Subject2, Value = Convert.ToDecimal(s2), });
marks.Add(Convert.ToInt32(id), list)
}
else
{
Console.WriteLine("id not found");
}
Hope this helps.