call methods from my class.cs - c#

i was need to write 2 methods in my student class which do the following
hasPassed() Should return True if the student has a year mark >= 40 or
false if the marks is <40
toString() Should return a single string containing a summary of the
student details held within the class
e.g.
“12345 Basil Fawlty, 23/08/1946”
here's the code i have for the above to methods, is what i have correct for what its asking for the above?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CourseWork
{
public class Student
{
private static string firstname;
private string secondname;
private string dateofbirth;
private string course;
private int matricnumber;
private double yearmark;
public bool hasPassed()
{
if (yearmark >= 40)
return true;
else
return false;
}
public void toString()
{
firstname = "Basil";
secondname = "Fawlty";
dateofbirth = "23/08/1946";
course = "MA Hotel Management";
matricnumber = 12345;
yearmark = 55;
}
public Student()
{
}
public string FirstName
{
get { return firstname; }
set { firstname = value; }
}
public string SecondName
{
get { return secondname; }
set { secondname = value; }
}
public string DateOfBirth
{
get { return dateofbirth; }
set { dateofbirth = value; }
}
public string Course
{
get { return course; }
set { course = value; }
}
public int MatricNumber
{
get { return matricnumber; }
set
{
if (value <= 99999 && value >= 10000)
{
matricnumber = value;
}
else
{
Console.WriteLine("Invalid Matric Number: {0}", value);
}
matricnumber = value;
}
}
public double YearMark
{
set
{
if (value <= 100 && value >= 0)
{
yearmark = value;
}
else
{
Console.WriteLine("Invalid Year Mark: {0}", value);
}
yearmark = value;
}
}
}
i then need the above methods to be used in a get button that does the following
Get: Uses the values of the Student class methods to update the text boxes. The
Student.hasPassed() method should be used to update the pass/fail label. The
Student details summary should be updated by using Student.toString ().
but I'm having trouble coding it and i cant seam to call hasPassed() method or toString() method from my student class
so I've doing something wrong but cant see what it is
any ideas how to go about fixing this?
i have a set button that basically lets me save update vaules in the student class, though i dont think thats saving them correcty, but wont know until i get the Get button working i have used Student student = new student() in the set button in the get button i need to use the toString method to show the eg 12345 Basil Fawlty, 23/08/194 in the txt boxes and in a label, i then need to use hasPassed() method in the Get button so that when a yearmark is >= 40 another label says Pass or fail if < 40

I dont completely read your question because there are lots of errors.
For example
public void toString()
{
firstname = "Basil";
secondname = "Fawlty";
dateofbirth = "23/08/1946";
course = "MA Hotel Management";
matricnumber = 12345;
yearmark = 55;
}
where is your object?
you should create an object like this:
Student stu = new Student();
Be careful and ask your question more understandable!
Have a look :
https://stackoverflow.com/questions/902994/how-to-ask-programming-questions-correctly

The firstName variable is static. This will make all instances of Student share the same first name, which is not correct. Each Student object should have it's own first name.
The class's instance variables are private and have no way of being set. You probably want to create a constructor that takes these variables as arguments.
public Student(string firstName, string secondName, ...)
{
this.firstName = firstName;
this.secondName = secondName;
...
}
The hasPassed() method is correct. You can verify that the behavior is working by instantiating an instance of the Student class and calling hasPassed() on the instantiated object.
double goodYearMark = 85;
Student goodStudent = new Student("Basil", "Fawlty", ..., goodYearMark);
Console.WriteLine("Good Student Passed? " + goodStudent.hasPassed());
double badYearMark = 35;
Student badStudent = new Student("Bad", "Student", ..., badYearMark);
Console.WriteLine("Bad Student Passed? " + badStudent.hasPassed());
The ToString() method should return a string value. Every object in .NET has a ToString() method, and you can override the default behavior using the override keyword.
See the MSDN documentation for the Object.ToString Method.
public override string ToString()
{
return string.format("{0} {1}, {2}", firstName, secondName, dateOfBirth);
}
The code examples above may not compile because I typed them directly into the response window, but hopefully they will be useful as guidance. Hope this helps!

Read the toString requirement one more time, you're doing this wrong. What happens to your existing values when you call toString in your code now?
Also, check the two last property setters. Currently you're not preventing the user setting an invalid value.
You also need to create an instance of your class, and set initial values on it that you can return from toString.
Good luck, you're almost there :-)

Related

UWP AutoGenerateProperty show two collections in DisplayMemberPathCollection

I'm trying to modify a comboBox or catalog from showing the property "Name" from a set of collections to show two of them, like "Name" and "Age" for example.
I have already tried to add it as a second parameter as
[DisplayMemberPathCollection("Name","SecondString")]
and modifying the attribute so it takes two parameters.
//The autogenerated property in the model:
[AutoGenerateProperty]
[Display("User")]
[PropertyOrder(1)]
[DisplayMemberPathCollection("Name")]
[SelectedItemCollection("SelectedUser")]
//I changed it to this:
[AutoGenerateProperty]
[Display("User")]
[PropertyOrder(1)]
[DisplayMemberPathCollection("Name","Age")]
[SelectedItemCollection("SelectedUser")]
//The attribute modification I made to get two parameters:
public DisplayMemberPathCollectionAttribute(string first = "", string second = "")
{
DisplayMemberPath = first + second;
}
I would like to have those two fields displayed in the combo, but anything just doesn't seem to work and I haven't found anything helpfull yet
What you're doing was impossible. The DisplayMemberPath doesn't support concatenated field name. The correct way is to create a new field to concatenate the two fields and make the 'DisplayMemberPathCollection' refer to the new field.
For example, you could define a 'FullName' in your model class:
public class User:PropertyChangeBase
{
private string name;
public string Name
{
get { return name; }
set
{
name = value;
NotifyPropertyChanged();
}
}
private string lastName;
public string LastName
{
get { return lastName; }
set
{
lastName = value;
NotifyPropertyChanged();
}
}
private string fullName;
public string FullName
{
get { return Name + " " + LastName; }
}
private int age;
public int Age
{
get { return age; }
set
{
age = value;
NotifyPropertyChanged();
}
}
}
The 'DisplayMemberPathCollection' looks like this: [DisplayMemberPathCollection("FullName")], then the comboBoxItem will show show the full name.

Convert object to string in C# [duplicate]

Okay, so I wrote this program from an exercise in a C# programming book (I'm trying to learn here) and it asks for "Override the ToString() method to return all data members".
Have I done this correctly? Or have I just successfully written code that compiles but does nothing? What is the purpose of ToString?
I have spent about 30 minutes looking at other posts on this and haven't figured it out, so I decided to make this.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication297
{
class Program
{
static void Main(string[] args)
{
String name = "Stormtrooper";
Employee s = new Employee(name);
Console.WriteLine("The type of hire is a {0}", s.Name);
Console.WriteLine("The identification number is {0}", s.Number);
Console.WriteLine("The date of hire is {0} ABY", s.Date);
Console.WriteLine("The standard galactic salary is...{0:C}", s.Salary);
}
class Employee
{
private string _name;
private string _number;
private int _date;
private int _salary;
public string Name
{
get
{
return _name;
}
}
public string Number
{
get
{
return _number;
}
}
public int Date
{
get
{
return _date;
}
}
public int Salary
{
get
{
return _salary;
}
}
public Employee(string n)
{
_name = n;
_number = "AA23TK421";
_date = 4;
_salary = 800;
}
}
public override string ToString()
{
return "_name + _number + _date + _salary".ToString();
}
}
}
You are returning a string that just says the phrase _name + _number + _date + _salary.
What you likely wanted to do is build a string using those fields. If you wanted them all mushed together Concat would work, but it would be highly un-readable
public override string ToString()
{
return String.Concat(_name, _number, _date, _salary);
}
However what would be better is to use Format and include labels with the values
public override string ToString()
{
return String.Format("Name:{0}, Number:{1}, Date:{2}, Salary:{3}",_name, _number, _date, _salary);
}
If you are using C# 6 or newer you can use the following cleaner format
public override string ToString()
{
return $"Name:{_name}, Number:{_number}, Date:{_date}, Salary:{_salary}";
}
Which is the exact same logic as the previous String.Format version.
The reason people override the ToString() method is to have a default string representation of your object, usually for display to the user or in a log or console, like this:
Console.WriteLine(yourClassObject);
If you do not override the ToString(), then its default implementation is to return the fully qualified name of your object, like this:
YourNamespace.YourClassName
By changing the inherited implementation (from System.Object), then you can make a nicer (read: prettier) representation, like this:
public override string ToString()
{
return String.Format("This instance of my object has the following: Name = {0}, Number = {1}, Date = {2}, Salary = ${3}", _name, _number, _date, _salary);
}
If you are using C# 6 (or later) use the nameof() method for the property names in the string in case the property names change. You can also use the $"" notation instead of using string.Format().
For example:
public override string ToString()
{
return $"{nameof(Name)}: {_name}";
}
Rather try something like
public override string ToString()
{
return String.Format("Name : {0}, number {1}, date {2}, salary {3}",_name,_number,_date,_salary);
}
But it neads to be part of the class
so
class Employee
{
private string _name;
private string _number;
private int _date;
private int _salary;
.....
public override string ToString()
{
return String.Format("Name : {0}, number {1}, date {2}, salary {3}",_name,_number,_date,_salary);
}
}
Have a look at String.Format Method
Replaces each format item in a specified string with the text
equivalent of a corresponding object's value.
You could try to format the output in a nice format. (not tested, though)
public override string ToString()
{
return string.Format("Name: {0} Number: {1:n0} Date: {2:yyyy-MM-dd} Salary: {3:n2}", _name, _number, _date, _salary);
}
there are a lot of purposes overwriting .ToString(), depending on the context. for example,
some developers like to have nicely formatted object description when doing debug, overwriting .ToString() would allow them to have meaningful description with some identifier (for example, the Id of a object);
Some developers like to put some serialization code into the ToString() method;
Some developers even put some debug code into the .ToString() method, though it might not be a good practice.
it really depending on the context of your needs. you may find some good practices to follow online - believe there are plenty of resources online.
Without overiding ToString, if you tried to "get" the string value of an Employee, e.g.
var employee1= new Employee();
Console.WriteLine(employee1);
What you'd get is:
ConsoleApplication1.Program+Employee
Which provides no information at all to help you (or a UI) display relevant information.
I use
return _name + _number + _date + _salary;
Which defaults to string,
or a more verbose
return "Name:" + _name + " Number:" + _number + " etc...";
class Program
{
static void Main( )
{
int Number = 10;
Console.WriteLine(Number.ToString());
Customer cc = new Customer();
cc.FirstName = "Rakibuz";
cc.LastName = "Sultan";
Console.WriteLine(Convert.ToString(cc));
}
}
public class Customer
{
public string FirstName;
public string LastName;
public override string ToString()
{
return FirstName + " " + LastName;
}
}

WindowsForms - How to cast an integer to String in C#

I am new to C# and I am creating a Form that is supposed to give the user the opportunity to enter name and age. Then, by submitting this information, there should be a summary(a new form) that shows what the user their input.
I finally got it working with the name, as it's a string and it's not a big deal, but I am stuck with the age.
I've tried casting, however, it does not work. I also looked at the documentation, but I do not find anything useful. Well, probably because I don't know where to look.
Anyway, I would strongly appreciate if someone give me an example for this.
Thanks in advance.
FormEnterDetails.cs
PersonStatic.LName = this.textBoxLastName.Text;
PersonStatic.Age = this.textBoxAge.Text;
DetailsHolder.cs
private string lName;
public string LName
{
get { return lName; }
set { lName = value; }
}
string age;
public String Age
{
get { return age; }
set { age = value; }
}
FormSummary.cs
private void FormSummary_Load(object sender, EventArgs e)
{
//we need to do this work on form load and not on creation
this.labelFirstNameSummary.Text = dh.FName;
this.labelLastNameSummary.Text = dh.LName;
this.labelAge.Text = Int32.Parse(dh.Age);
}
PersonStatic.cs
static string lName;
public static string LName
{
get { return PersonStatic.lName; }
set { PersonStatic.lName = value; }
}
static string age;
public static string Age
{
get { return PersonStatic.age;}
set { PersonStatic.age = value; }
}
I hope you want something like this
string ageString = ageInt.ToString();
Use the ToString() built-in function to convert anything to a string:
Int x=5;
String y;
y=x.ToString();
From the code you've posted, all places related to age appear to already be using string, not int (note that these are keywords that shorten the real type names, System.String and System.Int32). So you should be getting an error on this line:
this.labelAge.Text = Int32.Parse(dh.Age);
The Int32.Parse static method converts from a string to an int. (If you want to convert the other way, then as other answers have mentioned, you can call the ToString() instance method on your int.)
But in this case dh.Age, assuming dh is an instance of DetailsHolder, is already a string. And labelAge.Text, assuming labelAge is an instance of System.Windows.Forms.Label, is also a string. So you don't need to do any conversion:
this.labelAge.Text = dh.Age;

Why won't my objects print? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
New to the site as well as c#. This is my first time using c# and I can't get my objects to print properly. (example Million, Max 55. Cardenas, Jose, 22). I am pretty sure the error is in my accessors but I can't seem to get it right.
using System.IO;
using System;
class PersonApp
{
static void Main()
{
Random random = new Random();
Person p1 = new Person();
Person p2 = new Person();
p1.Fname = "Max";
p1.Lname = "Million";
p1.Id = random.Next(1,100);
p2.Fname = "Jose";
p2.Lname = "Cardenas";
p2.Id = random.Next(1,100);
Console.WriteLine(p1,p2);
}
}
using System.IO;
using System;
public class Person
{
private string Fname;
private string Lname;
private int Id;
public Person(){
Fname = string.empty;
Lname = string.empty;
Id = 0;
}
public string Fname
{
get
{
return Fname;
}
set
{
Fname = value;
}
}
public string Lname
{
get
{
return Lname;
}
set
{
Lname = value;
}
}
public int Id
{
get
{
return Id;
}
set
{
Id = value;
}
}
}
You have a few issues in your code.
First, you can't pass multiple values to Console.WriteLine like this:
Console.WriteLine(p1, p2);
Do one at a time:
Console.WriteLine(p1);
Console.WriteLine(p2);
Second, you can't name your private backing field and the public property used to get/set it the same. You can name them whatever you want... typically the private variable starts with a lower case or an underscore, but that's up to you.
Once you fix those, you'll still get unusual output, which is actually the full namespace of your class. That's the result of ToString() being implicitly called when you pass p1 to Console.WriteLine.
Override the ToString() method in your class:
public class Person
{
private string Fname;
private string Lname;
private int Id;
private override string ToString()
{
return string.Format("{0}, {1} {2}", Lname, Fname, Id);
}
...
...
}
You need to access property of the method to get the values printed
Wrong code :
Console.WriteLine(p1,p2); // You are trying to print Objects and this is wrong. !!
Correction : Use accessory's get to print the output.
Console.WriteLine(p1.Fname); // Print first name "Max"
Likewise
Console.WriteLine(p1.Lname); // print Last name
Console.WriteLine(p1.Id); // Print ID
Also your class need to be corrected
using System.IO;
using System;
public class Person{
private string fname;
private string lname;
private int id;
public string Fname
{
get
{
return fname;
}
set
{
fname = value;
}
}
public string Lname
{
get
{
return lname;
}
set
{
lname = value;
}
}
public int Id
{
get
{
return id;
}
set
{
id = value;
}
}
}
Now you can use it like
Person a = new Person();
a.Fname = "k";
a.Lname = "Do";
a.Id = 1024;
Console.WriteLine(a.Fname+" "+a.Lname+" "+a.Id);
You can't expect C# to know the format you want the object output in. You have to concatenate the strings yourself to produce the output.
The neatest way to do this is expose a readonly property on Person that formats it how you want, something like this:
public string DisplayName {
get {
return Lname + ", " + Fname + " " + Id;
}
}

Comparing two object state,before and after update

first things first.
I have the following classes:
class Employee
{
private int employeeID;
private string firstName;
private string lastName;
private bool eligibleOT;
private int positionID;
private string positionName;
private ArrayList arrPhone;
public IList<Sector> ArrSector {get; private set;}
//the constructor method takes in all the information of the employee
public Employee(int empID, string fname, string lname, bool elOT, int pos, string posname)
{
employeeID = empID;
firstName = fname;
lastName = lname;
eligibleOT = elOT;
positionID = pos;
positionName = posname;
arrPhone = new ArrayList();
ArrSector = new List<Sector>();
}
//the constructor method takes in the employee id, the first name and the last name of the employee
public Employee(int empid, string firstname,string lastname)
{
employeeID = empid;
firstName = firstname;
lastName = lastname;
}
//overtides the first name and the last name as a string.
public override string ToString()
{
return firstName +" "+lastName;
}
public int EmployeeID
{
get { return employeeID; }
set { employeeID = value; }
}
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
public string LastName
{
get { return lastName; }
set { lastName = value; }
}
public bool EligibleOT
{
get { return eligibleOT; }
set { eligibleOT = value; }
}
public int PositionID
{
get { return positionID; }
set { positionID = value; }
}
public string PositionName
{
get { return positionName; }
set { positionName = value; }
}
public ArrayList ArrPhone
{
get { return arrPhone; }
set { arrPhone = value; }
}
// The function assigns all the variables associated to the employee to a new object.
public static object DeepClone(object obj)
{
object objResult = null;
using (MemoryStream ms = new MemoryStream())
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms, obj);
ms.Position = 0;
objResult = bf.Deserialize(ms);
}
return objResult;
}
//Memento pattern is used to save the employee state.
//The changes will be rolled back if the update button not clicked
public class Memento : IMemento
{
private Employee originator = null;
private int employeeID;
private string firstName;
private string lastName;
private bool eligibleOT;
private int positionID;
private string positionName;
private ArrayList arrPhone;
private IList<Sector> arrSector;
public Memento(Employee data)
{
this.employeeID = data.EmployeeID;
this.firstName = data.FirstName;
this.lastName = data.LastName;
this.eligibleOT = data.EligibleOT;
this.positionID = data.PositionID;
this.positionName = data.PositionName;
this.arrPhone = data.ArrPhone;
this.originator = data;
this.arrSector = Extensions.Clone<Sector>(data.ArrSector);
}
}
I am using C sharp in winforms. the front end of my application has a listbox on the left end side which has the first name of the employee.on the left hand side, there are different textboxes which correspond to the employee selected in the list box. I have coded it in such a way that everytime i select an employee, its attributes, like the employee id, name, position, etc are displayed in these fields.
if the user changes any attribute of the employee, he has to click an update button to make the changes to the database.
now the real problem, when the user changes any field of the selected employee, and selects another employee without clicking the update button, i want to show a pop up box to tell the user that if he selects another employee , all the changes will be lost.
for this reason i have created the momento class to hold the previous state of the employee.
i have also tried overloading the == operator
public static bool operator ==(Employee e, Memento m)
{
return ((e.employeeID == m.employeeID) &&
(e.firstName == m.firstName) &&
e.lastName == m.lastName &&
e.eligibleOT == m.eligibleOT &&
e.positionID == m.positionID &&
e.positionName == m.positionName &&
e.arrPhone == m.arrPhone &&
e.ArrSector == m.arrSector);
}
public static bool operator !=(Employee e, Memento m)
{
return (e.employeeID != m.employeeID);
}
my idea was to compare the two object...
but m not successfull. how do i do it??how do i show the popup if changes are made.?where do i place the code to show the popup?
One word of warning...it's generally not a good idea to have different logic in your == and != operators. It's somewhat unintuitive to be able to have both == and != be false at the same time.
if(!(a == b) && !(a != b))
{
// head explodes
}
That aside, I'm guessing that you have your Employee class referenced as an object (or other parent class) in your comparison code. Maybe something like this:
if(listBox1.SelectedItem != currentMemento)
{
...
}
If this is the case, then the compiler isn't binding the != to your custom implementation. Cast listBox1.SelectedItem to Employee in order to force that.
if((Employee)listBox1.SelectedItem != currentMemento)
{
...
}
There are, however, many other approaches that you could take to solve this issue:
Make the implementation entirely on the GUI side, with a bool that gets set to true when the data in the text fields changes, then check that flag when changing employees
Implement the IComparable or IEquatable interfaces
Override the Equals method on the Employee and/or Memento class
(If you go with the second option, it's generally recommended that you complete the third as well)
Example
Here's an example of what you could do (I'm assuming you have a ListBox named listBox1 and you've attached to the SelectedIndexChanged event with the listBox1_SelectedIndexChanged function):
private Employee lastSelectedEmployee;
private Memento selectedMemento;
void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
Employee selectedEmployee = (Employee)listBox1.SelectedItem;
if(lastSelectedEmployee != null && lastSelectedEmployee != selectedEmployee)
{
if(/*changes exist*/)
{
if(/*cancel changes*/)
{
listBox1.SelectedItem = lastSelectedEmployee;
return;
}
}
}
lastSelectedEmployee = selectedEmployee;
selectedMemento = //create the memento based on selectedEmployee;
}
You'll have to provide your own logic for the areas I've left comments, but the idea should be pretty straightforward.
Have a look at the IComparable interface. It requires you to implement the method you need t make such a comparison. KB article, Hopefully it turn English for you, on my PC it turns always German.
-sa

Categories