Trying to learn to program and once again losing all confidence because I think I've internalised a simple concept but something seemingly extraordinary is happening or it is just flying right over my head.
When I run the program I get a StackOverFlowException if I access the property by assigning a string to FirstName or SecondName
My Customer Class:
class Customer : ICustomer
{
public string FirstName
{
get
{
return FirstName;
}
set
{
FirstName = value;
}
}
public string fName
{
get
{
return fName;
}
set
{
fName = value;
}
}
public string SecondName
{
get
{
return SecondName;
}
set
{
SecondName = value;
}
}
public string sName
{
get
{
return sName;
}
set
{
sName = value;
}
}
public int ID
{
get
{
return ID;
}
set
{
ID = value;
}
}
public int mId
{
get
{
return mId;
}
set
{
mId = value;
}
}
public int GetID()
{
return mId;
}
public void SetID(int id)
{
mId = ID;
}
public void SetName(string fName, string sName)
{
fName = FirstName;
sName = SecondName;
}
}
and the main program
class Program
{
/// <summary>
/// Create unique string code based off current date and time.
/// </summary>
/// <returns>code string</returns>
static string generateUniqueCode()
{
string characters = "abcdefghijklmnopqrstuvqxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
string ticks = DateTime.UtcNow.Ticks.ToString();
var code = "";
for (var i = 0; i < characters.Length; i += 2)
{
if ((i + 2) <= ticks.Length)
{
var number = int.Parse(ticks.Substring(i, 2));
if (number > characters.Length - 1)
{
var one = double.Parse(number.ToString().Substring(0, 1));
var two = double.Parse(number.ToString().Substring(1, 1));
code += characters[Convert.ToInt32(one)];
code += characters[Convert.ToInt32(two)];
}
else
code += characters[number];
}
}
return code;
}
/// <summary>
/// Creates unique integer code based off current date and time.
/// </summary>
/// <returns>integer code</returns>
static int generateUniqueCode(int seed)
{
string characters = "0123456789";
Random randInt = new Random(seed);
var ticks = randInt.Next();
int code = 0;
for (var i = 0; i < characters.Length; i += 2)
{
if ((i + 2) <= ticks)
{
var number = ticks;
if (number > characters.Length - 1)
{
var one = double.Parse(number.ToString().Substring(0, 1));
var two = double.Parse(number.ToString().Substring(1, 1));
code += characters[Convert.ToInt32(one)];
code += characters[Convert.ToInt32(two)];
}
else
code += characters[number];
}
}
return code;
}
static void Main(string[] args)
{
Customer customer = new Customer();
int generatedIntCode = generateUniqueCode(1);
customer.FirstName = "Conor";
customer.SecondName = "MacFirbhisigh";
customer.SetID(generatedIntCode);
Console.WriteLine("{0}, {1} {2}", customer.ID, customer.FirstName, customer.SecondName);
//Console.ReadKey();
}
}
In the getter and setter of FirstName (and all others), you are calling the same property over and over again. The endless loop you created will result in a StackOverflowException.
If you don't want to add custom logic to your properties, just use auto-implemented properties:
public string FirstName
{
get;
set;
}
If you did want to implement the property on your own, creating your own backing fields, this is what it should look like (this is effectively the same as what the above code would generate):
private string firstName; // backing field
public string FirstName
{
get
{
return this.firstName; // return the backing field
}
set
{
this.firstName = value; // set the backing field
}
}
You left out a few important parts
Firstly, you always need to declare you variables,
public - for outside get and set, thus no need for the get-set methods.
private - get/set methods are necessary for data retrieval modification.
Also, see the SetName method.
Hope it helps :p
This should do the trick:
class Customer : ICustomer
{
private string firstName;
private string name;
private string secondName;
private string sName;
private int iD;
private int mId;
public string FirstName
{
get
{
return firstName;
}
set
{
firstName = value;
}
}
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public string SecondName
{
get
{
return secondName;
}
set
{
secondName = value;
}
}
public string SName
{
get
{
return sName;
}
set
{
sName = value;
}
}
public int ID
{
get
{
return iD;
}
set
{
iD = value;
}
}
public int MId
{
get
{
return mId;
}
set
{
mId = value;
}
}
public void SetName(string fName, string sName)
{
FirstName = fName;
SecondName = sName ;
}
}
Related
I am trying to create a class that contains a header for my list-box. I have two classes that I will be inserting in the listbox. The first class runs fine, but the second one I am making so that the array is entirely of strings is telling me that a method must have a value return type. What does this mean exactly? The error at hand is "HeaderItems."
namespace RETAILITEMSBLAKE
{
class HeaderClass
{
string HeaderDescription;
string HeaderPrice;
string HeaderUnitsonHand;
public HeaderItems(string HeaderDescription, string HeaderUnitsonHand, string HeaderPrice)
{
this.HeaderDescription = HeaderDescription;
this.HeaderUnitsonHand = HeaderUnitsonHand;
this.HeaderPrice = HeaderPrice;
}
public string HeaderDescriptions
{
get
{
return HeaderDescription;
}
set
{
HeaderDescription = value;
}
}
public string HeaderUnits
{
get
{
return HeaderUnitsonHand;
}
set
{
HeaderUnitsonHand = value;
}
}
public string HeaderPrices
{
get
{
return HeaderPrice;
}
set
{
HeaderPrice = value;
}
}
}
Here is my first class that is working correctly:
namespace RETAILitemsBLAKE
{
class ItemizedClass
{
string description;
int unitsonhand;
double price;
public ItemizedClass(string description,int unitsonhand,double price)
{
this.description = description;
this.unitsonhand = unitsonhand;
this.price = price;
}
public string Description
{
get
{
return description;
}
set
{
description = value;
}
}
public double Price
{
get
{
return price;
}
set
{
price = value;
}
}
public int Quantity
{
get
{
return unitsonhand;
}
set
{
unitsonhand = value;
}
}
}
}
So, my goal is to have the HeaderClass so that I can place them as headers in my Listbox. Is there an alternate way to do such? I want to place it on top of the code here:
namespace RETAILitemsBLAKE
{
public partial class FrmItemList : Form
{
ItemizedClass[] items;
public FrmItemList()
{
InitializeComponent();
ItemizedArray();
}
private void ItemizedArray()
{
ItemizedClass jackets = new ItemizedClass("Jackets", 12, 59.95);
ItemizedClass jeans = new ItemizedClass("Jeans", 40, 34.95);
ItemizedClass shirts = new ItemizedClass("Shirts", 20, 24.95);
items = new ItemizedClass[] { jackets, jeans, shirts };
foreach (ItemizedClass RetailData in items)
{
lstRetailitems.Items.Add(RetailData.Description + "\t\t" + RetailData.Quantity + "\t" + "$" + RetailData.Price);
}
}
}
}
Would anyone be of assistance? Thank you!
You are using construct method which needs as same as class name and it didn't need to set return data type, so the method name needs to write HeaderClass in HeaderClass class otherwise it needs to set return data type to be a normal method.
class HeaderClass
{
string HeaderDescription;
string HeaderPrice;
string HeaderUnitsonHand;
public HeaderClass(string HeaderDescription, string HeaderUnitsonHand, string HeaderPrice)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
namespace MyNamespace
{
class Student
{
private string _name;
private int _phoneNo;
private string _address;
private string _occupation;
private string _courseOfStudy;
private int _duration;
private string _uploadPicture;
}
public string Name
{
get { return _name;}
set { _name = value;}
}
public int PhoneNumber
{
get { return _phoneNo;}
set { _phoneNo = value;}
}
public string Address
{
get { return _address;}
set { _address = value;}
}
public string Occupation
{
get { return _occupation;}
set { _occupation = value;}
}
public string CourseOfStudy
{
get { return _courseOfStudy;}
set { _courseOfStudy = value;}
}
public int Duration
{
get { return _duration;}
set { _duration = value;}
}
public string Uploadpicture
{
get { return _uploadpicture;}
set { _uploadpicture = value;}
}
public Student()
{
_name = "";
_phoneNo = "";
_address = "";
_occupation = "";
_courseOfStudy = "";
_duration = "";
_uploadPicture = "";
System.Windows.Forms.MessageBox.Show("Called Constructor")
}
public Student (String name, int phoneNo, string address, string occupation, string courseOfStudy, int duration, string uploadPicture)
{
_name = name;
_phoneNo = phoneNo;
_address = address;
_occupation = occupation;
_courseOfStudy = courseOfStudy;
_duration = duration;
_uploadPicture = uploadPicture;
}
}
You cannot declare methods outside of a class in C#.
Remove that first }
it is causing the properties below it to appear outside of the class.
As others have pointed out, you have put all your properties and constructors outside the class. Also you have large amounts of unnecessary code for handling the properties, as you are not encapsulating the field values in any way. So they can be rewritten to use auto properties. Try the following rewrite:
namespace MyNamespace
{
class Student
{
public string Name { get; set; }
public int PhoneNumber { get; set; }
public string Address { get; set; }
public string Occupation { get; set; }
public string CourseOfStudy { get; set; }
public int Duration { get; set; }
public string UploadPicture { get; set; }
public Student() : this("", 0, "", "", "", 0, "")
{
MessageBox.Show("Called Constructor");
}
public Student(String name, int phoneNo, string address, string occupation, string courseOfStudy, int duration, string uploadPicture)
{
Name = name;
PhoneNumber = phoneNo;
Address = address;
Occupation = occupation;
CourseOfStudy = courseOfStudy;
Duration = duration;
UploadPicture = uploadPicture;
}
}
}
The members are courrently not inside your class. The curly bracket behind _uploadPicture; } shuld be at the end.
Also, there a some other mistakes:
_uploadpicture should be _uploadPicture in public string Uploadpicture
you are trying to initialise an int with an string (_phoneNo = "";)
Here is the corrected class:
namespace MyNamespace {
class Student {
private string _name;
private int _phoneNo;
private string _address;
private string _occupation;
private string _courseOfStudy;
private int _duration;
private string _uploadPicture;
public string Name {
get {
return _name;
}
set {
_name = value;
}
}
public int PhoneNumber {
get {
return _phoneNo;
}
set {
_phoneNo = value;
}
}
public string Address {
get {
return _address;
}
set {
_address = value;
}
}
public string Occupation {
get {
return _occupation;
}
set {
_occupation = value;
}
}
public string CourseOfStudy {
get {
return _courseOfStudy;
}
set {
_courseOfStudy = value;
}
}
public int Duration {
get {
return _duration;
}
set {
_duration = value;
}
}
public string Uploadpicture {
get {
return _uploadPicture;
}
set {
_uploadPicture = value;
}
}
public Student() {
_name = "";
_phoneNo = 0;
_address = "";
_occupation = "";
_courseOfStudy = "";
_duration = 0;
_uploadPicture = "";
System.Windows.Forms.MessageBox.Show("Called Constructor");
}
public Student(string name, int phoneNo, string address, string occupation, string courseOfStudy, int duration, string uploadPicture) {
_name = name;
_phoneNo = phoneNo;
_address = address;
_occupation = occupation;
_courseOfStudy = courseOfStudy;
_duration = duration;
_uploadPicture = uploadPicture;
}
}
}
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?
In order the methods to be visible, you need to create an instance of the class Student. ex,
Student _student = new Student();
bool _x = _student.hasPassed();
if you want the members to be access without instantiating, make the member static,
public static bool hasPassed()
{
if (yearmark >= 40)
return true;
else
return false;
}
but bear in mind that static members cannot see non-static members. In that case, it won;t compile because yearmark cannot be found.
I am totally unable to access the outer class attributes inside the inner class ...
even if i make object of outer class,, in inner class*which makes no sense in composition design* .. even then i cant access them ..
is there a way by which i can access these outer class attributes ?
Scenario is that there is some sports car which is constructed only if the customers who want to buy it exists! ..
namespace composition{
public class CustomCar
{
#region Attributes
private string name;
private string plateno;
private double cost;
private CarCustomer _customer = new CarCustomer();
#endregion
#region properties
public string Name
{
get { return name; }
set { name = value; }
}
public double Cost
{
get { return cost; }
set { cost = value; }
}
public string PlateNo
{
get { return plateno; }
set { plateno = value; }
}
public CarCustomer Customer
{
get { return _customer; }
set { _customer = value; }
}
#endregion
#region methods
public CustomCar()
{
Console.WriteLine("I am in custom car");
}
public CustomCar(string s1, string pno, double c, string s2, double n, double bc)
{
this.Name = s1;
this.PlateNo = pno;
this.Cost = c;
this.Customer.Name1 = s2;
this.Customer.Nic1 = n;
this.Customer.BargainCost = bc;
}
public double finalCost()
{
if (this.Customer.BargainCost < 10000)
{
double FinalCost = (this.Cost - this.Customer.BargainCost);
return FinalCost;
}
else
{
return this.Cost;
}
}
public void show()
{
Console.WriteLine(this.name + this.PlateNo + this.Customer.Name1 + this.Customer.Nic1);
}
#endregion
public class CarCustomer
{
private string name1;
private double Nic;
private double bargainCost;
public double BargainCost
{
get { return bargainCost; }
set { bargainCost = value; }
}
public double Nic1
{
get { return Nic; }
set { Nic = value; }
}
public string Name1
{
get { return name1; }
set { name1 = value; }
}
public CarCustomer()
{
Console.WriteLine("I have a customer");
}
public CarCustomer(string n1, double i1, double bc)
{
this.Name1 = n1;
this.Nic = i1;
this.BargainCost = bc;
}
public void showCustomer()
{
Console.WriteLine("Customer name: " + Name1);
Console.WriteLine("Customer NIC: " + Nic1);
}
}
}
}
There is nothing stopping you having a reference in the CarCustomer to the CustomCar object as well. This would then give you a one to one reference between the object. Were you instaiate this object is up to you in the Constructor of the CustomCar
public CustomCar(arguments)
{
this.Customer.CustomCar = this;
}
Or you could set it in the sets on the property accessors up to you. Try this
public class CustomCar
{
private string name;
private string plateno;
private double cost;
private CarCustomer _customer = new CarCustomer();
public string Name
{
get { return name; }
set { name = value; }
}
public double Cost
{
get { return cost; }
set { cost = value; }
}
public string PlateNo
{
get { return plateno; }
set { plateno = value; }
}
public CarCustomer Customer
{
get { return _customer; }
set { _customer = value; }
}
public CustomCar()
{
Console.WriteLine("I am in custom car");
}
public CustomCar(string name, string pno, double c, string customerName, double n, double bc)
{
this.Name = name;
this.PlateNo = pno;
this.Cost = c;
this.Customer.Name1 = customerName;
this.Customer.Nic1 = n;
this.Customer.BargainCost = bc;
this.Customer.Car = this;
}
public double finalCost()
{
if (this.Customer.BargainCost < 10000)
{
double FinalCost = (this.Cost - this.Customer.BargainCost);
return FinalCost;
}
else
{
return this.Cost;
}
}
public void show()
{
Console.WriteLine(this.name + this.PlateNo + this.Customer.Name1 + this.Customer.Nic1);
}
}
public class CarCustomer
{
private string name1;
private double Nic;
private double bargainCost;
private CustomCar customer;
public double BargainCost
{
get { return bargainCost; }
set { bargainCost = value; }
}
public double Nic1
{
get { return Nic; }
set { Nic = value; }
}
public string Name1
{
get { return name1; }
set { name1 = value; }
}
public CustomCar Car
{
get{return customer;}
set{customer = value;}
}
public CarCustomer()
{
Console.WriteLine("I have a customer");
}
public CarCustomer(string n1, double i1, double bc)
{
this.Name1 = n1;
this.Nic = i1;
this.BargainCost = bc;
}
public void showCustomer()
{
Console.WriteLine("Customer name: " + Name1);
Console.WriteLine("Customer NIC: " + Nic1);
}
}
Of course you can't access them. You've set their protection level to private. In order to get at them from an external resource their protection level has to be in line with the access level needed. In this case you should be able to change the modifier to protected and be able to access them.
However, looking at your class design, I think you would be better served using the automatic getter/setter syntax. You aren't doing anything particularly special in your property definitions, so it would make sense to get rid of the private variables and change your properties to this:
public string Name { get; set; }
public double Cost { get; set; }
public string PlateNo { get; set; }
public CarCustomer Customer { get; set; }
You'll still have public access to the variables through the properties and you won't have all the messiness of the extra variables.
I've been trying for hours to get many-to-many relationship to save with Castle ActiveRecord. What am I doing wrong? I can't find anything in the documentation or on google. There is data in the database.
Courses have a many to many relationship with Books.
Test code.
Database.Course c = new Database.Course();
c.Number = "CS 433";
c.Name = "Databases";
c.Size = 34;
c.Books = Database.Book.FindAll();
c.Save();
Also doesn't work
foreach(Database.Book b in Database.Book.FindAll()){
c.Books.Add(b);
}
Database Classes
[ActiveRecord]
public class Course : ActiveRecordValidationBase<Course>
{
private int? id;
private string number;
private string name;
private string description;
private int size; //number of students in class
//references
private IList books = new ArrayList();
public override string ToString()
{
return FormattedName;
}
public string FormattedName
{
get
{
return string.Format("{0} - {1}", Number, Name);
}
}
[PrimaryKey]
public int? Id
{
get { return id; }
set { id = value; }
}
[Property, ValidateNonEmpty]
public string Number
{
get { return number; }
set { number = value; }
}
[Property, ValidateNonEmpty]
public string Name
{
get { return name; }
set { name = value; }
}
[Property(ColumnType="StringClob")]
public string Description
{
get { return description; }
set { description = value; }
}
[Property]
public int Size
{
get { return size; }
set { size = value; }
}
[HasAndBelongsToMany(typeof(Book),
Table = "BookCourse", ColumnKey = "course_id", ColumnRef = "book_id", Inverse = true)]
public IList Books
{
get { return books; }
set { books = value; }
}
}
[ActiveRecord]
public class Book : ActiveRecordValidationBase<Book>
{
private int? id;
private string title;
private string edition;
private string isbn;
private bool is_available_for_order;
//relations
private IList authors = new ArrayList();
private IList bookordercount = new ArrayList();
private IList courses = new ArrayList();
private Inventory inventory;
public override string ToString()
{
return FormattedName;
}
public string FormattedName
{
//*
get {
string str;
if (Edition == null || Edition == "")
str = Title;
else
str = string.Format("{0} ({1})", Title, Edition);
if (Authors.Count != 0)
{
return string.Format("{0} by {1}", str, FormattedAuthors);
}
else
{
return str;
}
}
/*/
get
{
return Title;
}
//*/
}
public string FormattedAuthors
{
get
{
if (Authors.Count == 0) return "";
StringBuilder sb = new StringBuilder();
int i = 0, end = Authors.Count;
foreach (Author a in Authors)
{
i++;
sb.Append(a.FormattedName);
if (i != end) sb.Append("; ");
}
return sb.ToString();
}
}
[PrimaryKey]
public int? Id
{
get { return id; }
set { id = value; }
}
[Property, ValidateNonEmpty]
public string Title
{
get { return title; }
set { title = value; }
}
[Property]
public string Edition
{
get { return edition; }
set { edition = value; }
}
[Property, ValidateNonEmpty]
public string Isbn
{
get { return isbn; }
set { isbn = value; }
}
[Property]
public bool IsAvailableForOrder
{
get { return is_available_for_order; }
set { is_available_for_order = value; }
}
//relations
[HasAndBelongsToMany(typeof(Author),
Table = "BookAuthor", ColumnKey = "book_id", ColumnRef = "author_id")]
public IList Authors
{
get { return authors; }
set { authors = value; }
}
[HasMany(typeof(BookOrderCount), Table = "BookOrderCounts", ColumnKey = "BookId")]
public IList BookOrderCount
{
get { return bookordercount; }
set { bookordercount = value; }
}
[HasAndBelongsToMany(typeof(Course),
Table = "BookCourse", ColumnKey = "book_id", ColumnRef = "course_id")]
public IList Courses
{
get { return courses; }
set { courses = value; }
}
[OneToOne]
public Inventory Inventory
{
get { return inventory; }
set { inventory = value; }
}
}
Make sure you put the Inverse = true where you want it. From the Castle AR docs,
It is wise to choose one side of the
relation as the owner. The other side,
the non-writable, need to use
Inverse=true.
Put the Inverse = true on the other side of the relationship, like this:
[HasAndBelongsToMany(typeof(Book),
Table = "BookCourse", ColumnKey = "course_id", ColumnRef = "book_id")]
public IList<Book> Books
[HasAndBelongsToMany(typeof(Course),
Table = "BookCourse", ColumnKey = "book_id", ColumnRef = "course_id", Inverse = true)]
public IList<Course> Courses
You also have to add attributes to the top of both classes - at the moment they don't know what tables they're mapped to. Currently you have this:
public class Course : ActiveRecordBase<Course>
Add this (where "course" is the name of your Course table):
[ActiveRecord("course")]
public class Course : ActiveRecordBase<Course>