C# Inconsistent accessibility error - c#

I am having trouble to fix the errors in my object oriented program in C#. The program has 9 classes and in the one class. The Error is Inconsistent accessibility: parameter type 'Employee.Employee' is less accessible than method 'Employee.EmployeeInput.CollectEmployeeInfo(Employee.Employee)'
on the coding
public static void CollectEmployeeInfo(Employee theEmployee)
{
theEmployee.Firstname = InputUtilities.getStringInputValue("First Name");
theEmployee.Lastname = InputUtilities.getStringInputValue("Last name");
theEmployee.Gender = InputUtilities.getCharInputValue("Gender");
theEmployee.Dependents = InputUtilities.getIntegerInputValue("# Dependents");
}
the CollectEmployeeInfo is what is showing the error and I am not sure what has to be done to the other classes to fix the error. Any help would be greatly appreciated
class Employee
{
public const double MIN_SALARY = 20000;
public const double MAX_SALARY = 100000;
public const int MIN_DEPENDENTS = 0;
public const int MAX_DEPENDENTS = 10;
public const string DEFAULT_NAME = "not given";
public const char DEFAULT_GENDER = 'U';
public const string DEFAULT_TYPE = "Generic Employee";
protected string firstName;
protected string lastName;
protected double annualSalary;
protected char gender;
protected int dependents;
protected static int numEmployees = 0;
protected Benefits employeeBenefits;
protected string employeeType;
public Employee()
{
firstName = DEFAULT_NAME;
lastName = DEFAULT_NAME;
annualSalary = MIN_SALARY;
dependents = MIN_DEPENDENTS;
numEmployees++;
employeeBenefits = new Benefits();
}
public Employee(string firstname, string lastname, char gender, int dependents, double annualsalary, Benefits employeeBenefits)
{
Firstname = firstname;
Lastname = lastname;
AnnualSalary = annualsalary;
Gender = gender;
Dependents = dependents;
EmployeeBenefits = employeeBenefits;
numEmployees++;
}
public Benefits EmployeeBenefits
{
get { return employeeBenefits; }
set
{
if (value == null)
employeeBenefits = new Benefits();
else
employeeBenefits = value;
}
}
public Employee(string employeeType)
: this()
{
EmployeeType = employeeType;
}
public string Firstname
{
get { return firstName; }
set
{
if (String.IsNullOrEmpty(value))
firstName = DEFAULT_NAME;
else
firstName = value;
}
}
public string Lastname
{
get { return lastName; }
set
{
if (String.IsNullOrEmpty(value))
lastName = DEFAULT_NAME;
else
lastName = value;
}
}
public double AnnualSalary
{
get { return annualSalary; }
set
{
if (value > MIN_SALARY & value < MAX_SALARY)
annualSalary = value;
else if (value < MIN_SALARY)
annualSalary = MIN_SALARY;
else
annualSalary = MAX_SALARY;
}
}
public char Gender
{
get { return gender; }
set
{
if (value == 'F')
gender = value;
else if (value == 'f')
gender = value;
else if (value == 'M')
gender = value;
else if (value == 'm')
gender = value;
else
gender = DEFAULT_GENDER;
}
}
public int Dependents
{
get { return dependents; }
set
{
if (value >= MIN_DEPENDENTS & value <= MAX_DEPENDENTS)
dependents = value;
else if (value < MIN_DEPENDENTS)
dependents = MIN_DEPENDENTS;
else
dependents = MAX_DEPENDENTS;
}
}
public static int NumEmployees
{
get { return numEmployees; }
}
public string EmployeeName
{
get { return firstName + " " + lastName; }
}
public string EmployeeType
{
get { return employeeType; }
set
{
if (String.IsNullOrEmpty(value))
employeeType = DEFAULT_TYPE;
else
employeeType = value;
}
}
public double CalculatePay()
{
return annualSalary / 52;
}
public double CalculatePay(double modifiedSalary)
{
AnnualSalary = modifiedSalary;
return AnnualSalary / 52;
}
public override string ToString()
{
string output;
output = "\n============ Employee Information ============";
output += "\n\t Type:\t" + employeeType;
output += "\n\t Name:\t" + firstName + " " + lastName;
output += "\n\t Gender:\t" + gender;
output += "\n\t Dependents:\t" + dependents;
output += "\n\tAnnual Salary:\t" + annualSalary.ToString("C2");
output += "\n\t Weekly Pay:\t" + CalculatePay().ToString("C2");
output += "\n\t" + employeeBenefits.ToString();
return output;
}
}
}

Employee type should be not less accessible than CollectEmployeeInfo.
So Employee should be defined as public "at least"

All of the types you need to pass to a method must be at least as accessible as that method. If Employee is a private or internal class it can't be passed to this method from outside that class/assembly.
Make Employee public and it should work.

Related

Using the get;set statements to exclude values greater than or less than in C#

I've been following a tutorial online that looks at students, their subject and grade.and I've been introduced to the get and set statements. How would I ammend them the class to include "NA" for a grade that is =<0 or >5.3?
I still want to maintain a grade > 3.5 is an honours
class Student
{
public string Name;
public string Subject;
public double Grade;
public Student(string aName, string aSubject, double aGrade)
{
Name = aName;
Subject = aSubject;
Grade = aGrade;
}
public double grade
{
get { return Grade; }
set {
if (value > 5.3 || value <= 0)
{ grade = string "na";
}
else
{ grade = value;
}
public bool HasHonours()
{ if (Grade >= 3.5)
{
return true;
}
return false;
}
}
}
}
It was just needing the NaN operator:
namespace student
{
class Student
{
public string Name;
public string Subject;
public double Grade;
public Student(string aName, string aSubject, double Grade)
{
Name = aName;
Subject = aSubject;
grade=Grade;
}
private double grade
{
get { return Grade; }
set
{
if (value > 5.3 || value <= 0)
{
Grade = Double.NaN;
}
else
{
Grade = value;
}
}
}
public bool HasHonours()
{
if (grade >= 3.5)
{
return true;
}
else
{
return false;
}
}
}
}
Try this.
class Student
{
public string Name { get; set; };
public string Subject { get; set; };
public double Grade
{
get
{
return Grade;
}
set
{
// value is less than or equal to '0' or greater than '5.3' so return 'N/A'
if(!(value <= 0 || value > 5.3))
Grade = value;
}
};
public Student(string name, string subject, double grade)
{
this.Name = name;
this.Subject = subject;
this.Grade = grade;
}
public bool HasHonours()
{
if (grade > 3.5)
{
return true;
}
else
{
return false; // Because - Grade is Less than or equal to 3.5
}
}
}

How do I call static from the class I created in c#

namespace HelloDogs
{
class Dog
{
private string barkSound;
private string breed; // Added dogHeight, dogColor and noOfLegs to
private int dogHeight; // the private variable
private string dogColor;
private static int noOfLegs;
public string Breed
{
get { return breed; }
set { breed = value; }
}
public static int NoOfLegs
{
get{return noOfLegs; } // I created properties to encapsulate the variables
set {noOfLegs = value; } // dogHeight, dogColor and noOfLegs using the properties
}
public int DogHeight
{
get {return dogHeight;}
set{dogHeight = value;}
}
public string DogColor
{
get {return dogColor;}
set{ dogColor = value;}
}
private string dogSpeech;
public Dog()
{
barkSound = "Jack!";
breed = "cocker spaniel";
}
// Added a new constructor below that takes the following parameters
public Dog(int h,string b, string c )
{
dogHeight = h;
dogColor = c;
breed = b;
}
// A private method to check the dogHeight if true or false
private bool IsBig(int x)
{
if (x < 50)
return false;
else
return true;
}
// Change the GetSpeech method below to display all details about the dog
public string GetSpeech()
{
dogSpeech = "Hello, I am a " + breed + " , " + dogHeight + "cm" + ","
+ dogColor + "." + barkSound ;
return dogSpeech;
if(IsBig(dogHeight))
{
return dogSpeech = "You are big ";
} else
{
dogSpeech = " You are not big enough";
}
}
public void SetSound(String barkSound)
{
this.barkSound = barkSound;
}
}
}
Calling static from class please see this in msdn
https://msdn.microsoft.com/en-us/library/79b3xss3.aspx

Why isn't my property doing the check?

My constructor get info from the form. The 'name' is addressed with 'aName' (from the constructor), then there has to be a check done with prop 'NameCheck'. but if I compile it, it return an empty string. Any ideas?
Code:
---- Class ----
//Fields
private List<Create> Characters;
private string name;
private int health;
private int mSpeed;
private Role role;
private Speciality speciality;
//Properties
public string NameCheck
{
get {
return name;
}
set
{
if (string.IsNullOrEmpty(name))
{
name = "Name not specified";
}
else
{
name = value;
}
}
}
//Constructor
public Create(string aName, int aHealth, int aMSpeed, Role aRole, Speciality aSpeciality)
{
this.name = aName;
this.health = aHealth;
this.mSpeed = aMSpeed;
this.role = aRole;
this.speciality = aSpeciality;
Characters = new List<Create>();
}
---- Form ----
Create character = new Create(tbName.Text, health, mspeed, aLane, aSpecial);
Characters.Add(character);
cbSummary.Items.Add(character.ToString());
PS: cbSummary is a combobox.
EDIT:
public override string ToString()
{
return "Name: " + NameCheck + " - Health: " + health + " - MovementSpeed: " + mSpeed + " - Role: " + role + " - Speciality: " + speciality;
}
You should set this.NameCheck instead of this.name in your constructor
public Create(string aName, int aHealth, int aMSpeed, Role aRole, Speciality aSpeciality)
{
this.NameCheck = aName;
also you should check value for emptiness or being null instead of name in your property setter
set
{
if (string.IsNullOrEmpty(value))
{
You have a small typo in your property:
public string NameCheck
{
get {
return name;
}
set
{
// You need to check value, not name.
if (string.IsNullOrEmpty(value))
{
name = "Name not specified";
}
else
{
name = value;
}
}
}
In your constructor you should use your NameCheck property rather than the name field:
public Create(string aName, int aHealth, int aMSpeed, Role aRole, Speciality aSpeciality)
{
this.NameCheck = aName;
this.health = aHealth;
this.mSpeed = aMSpeed;
this.role = aRole;
this.speciality = aSpeciality;
Characters = new List<Create>();
}
Also as Paddy said you are doing an incorrect check in the set body of NameCheck:
public string NameCheck
{
get
{
return name;
}
set
{
if (string.IsNullOrEmpty(value))
{
name = "Name not specified";
}
else
{
name = value;
}
}
}

DataReader problems getting data from 2 classes

I am very inexperienced with SQL, and have only had one lesson. I am trying to figure out how to get information from 2 classes using a DataReader.
My Customer class:
public class Customer
{
private CreditCard _creditCard;
private List<Subscription> _subscriptions;
private int _customerId;
private string _name;
private string _address;
private int _zipCode;
private string _city;
private string _email;
private string _password;
public Customer(int id, string name, string email, string password)
{
this._customerId = id;
this._name = name;
this._email = email;
this._password = password;
this._subscriptions = new List<Subscription>();
}
public Customer(int id, string name)
{
this._customerId = id;
this._name = name;
_subscriptions = new List<Subscription>();
}
public override string ToString()
{
return _customerId + " " + _name;
}
public int CustomerId
{
get { return _customerId; }
set { _customerId = value; }
}
public string Name
{
get { return _name; }
set { _name = value; }
}
public string Address
{
get { return _address; }
set { _address = value; }
}
public int ZipCode
{
get { return _zipCode; }
set { _zipCode = value; }
}
public string City
{
get { return _city; }
set { _city = value; }
}
public string Email
{
get { return _email; }
set { _email = value; }
}
public string Password
{
get { return _password; }
set { _password = value; }
}
public List<Subscription> Subscriptions
{
get { return _subscriptions; }
}
public void AddSubscription(Subscription s)
{
_subscriptions.Add(s);
}
public Subscription FindSubscription(int sId)
{
bool found = false;
int i = 0;
while (!found && i < _subscriptions.Count)
{
if (_subscriptions[i].SubscriptionId == sId)
found = true;
else
i++;
}
if (found)
return _subscriptions[i];
else
return new Subscription();
}
}
My Subscription Class:
public class Subscription
{
private SubscriptionType _subscriptionType;
private CarModel _carModel;
private List<Booking> _bookings;
private int _subscriptionId;
public Subscription(int subscriptionId, SubscriptionType subscriptionType, CarModel carModel)
{
this._subscriptionId = subscriptionId;
this._subscriptionType = subscriptionType;
this._carModel = carModel;
_bookings = new List<Booking>();
}
public Subscription()
{ }
public int SubscriptionId
{
get { return _subscriptionId; }
set { _subscriptionId = value; }
}
public SubscriptionType SubscriptionType
{
get { return _subscriptionType; }
}
public CarModel CarModel
{
get { return _carModel; }
}
public override string ToString()
{
return this.SubscriptionId + "\t " + this.SubscriptionType + "\t " + this.CarModel;
}
}
My Database class:
public class DBCustomer
{
private static SqlCommand dbCmd = null;
public static List<Customer> GetCustomers()
{
List<Customer> returnList = new List<Customer>();
string sql = "select * from Customer";
dbCmd = AccessDBSQLClient.GetDbCommand(sql);
IDataReader dbReader;
dbReader = dbCmd.ExecuteReader();
Customer c;
while (dbReader.Read())
{
c = new Customer(Convert.ToInt32(dbReader["cId"].ToString()), dbReader["cName"].ToString());
returnList.Add(c);
}
AccessDBSQLClient.Close();
return returnList;
}
public static List<Customer> GetCustomersByEmail(string email)
{
List<Customer> returnList = new List<Customer>();
string sql = "select * from Customer where cEmail = '" + email+"'";
dbCmd = AccessDBSQLClient.GetDbCommand(sql);
IDataReader dbReader;
dbReader = dbCmd.ExecuteReader();
Customer c;
while (dbReader.Read())
{
c = new Customer(Convert.ToInt32(dbReader["cId"].ToString()), dbReader["cName"].ToString());
returnList.Add(c);
}
AccessDBSQLClient.Close();
return returnList;
}
public static List<Subscription> GetCustomerSubscriptions(int cId)
{
List<Subscription> returnList = new List<Subscription>();
string sql = "select S.sId, ST.stName,CM.cmDescription "
+ "from Customer C, Subscription S, SubscriptionType ST, CarModel CM "
+ "where C.cId = S.cId "
+ "and S.stId = ST.stId "
+ "and S.cmId = CM.cmId "
+ "and C.cId = " + cId;
dbCmd = AccessDBSQLClient.GetDbCommand(sql);
IDataReader dbReader;
dbReader = dbCmd.ExecuteReader();
Subscription s;
while (dbReader.Read())
{
//s = new Subscription();
s = new Subscription((int)(dbReader["sId"]).ToString(),
dbReader["stName"],
dbReader["cmDescription"]);
returnList.Add(s);
}
AccessDBSQLClient.Close();
return returnList;
}
Obviously the GetCustomers and GetCustomersByEmail methods are working, but I have no idea how to make the GetCustomerSubscriptions method, as it has to return data fra 2 classes, and I cant just build a Customer to add to the resultset.

C# array - "object reference not set to an instance of an object"

I am having a major issue making this work. All I need to do is make my array display.
namespace OOP_3
{
public partial class Add_Child : Form
{
public Add_Child()
{
InitializeComponent();
}
private void btnAddChild_Click(object sender, EventArgs e)
{
Mother m = new Mother();
m.MyChildren = new Child[3];
int ID = int.Parse(txtID.Text);
string FNAME = txtFname.Text;
string LName = txtLname.Text;
DateTime DOB = DateTime.Parse(txtDob.Text);
//Add children
label5.Text = m.GetMyChildrenDetails();
if (addtoarray(m,ID,FNAME,LName,DOB) == true)
{
MessageBox.Show("added", "Add Child");
}
else
{
MessageBox.Show("cannot add", "Child add - full");
}
}
public bool addtoarray(Mother m, int ID, string FNAME, string LName,DateTime DOB)
{
for (int i = 0; i < m.MyChildren.Length; i++)
{
if (m.MyChildren[i]== null)
{
m.MyChildren[i] = new Child(m); //See comment below
m.MyChildren[i].ChildId = ID;
m.MyChildren[i].FirstName = FNAME;
m.MyChildren[i].LastName = LName;
m.MyChildren[i].DateOfBirth = DOB;
return true;
}
}
return false;
}
}
}
From a code comment: This line destroys everything in the heap and recreate the array causing my to have values that will not show up in my label5.text ive been pondering researching for hours and i think iam either going insane or am just noobie at coding which iam :) please some help would be nice:)....
If needed, I will post my class's and main form up :)
public class Mother
{
//Fields
private int motherId;
private string firstName;
private string lastName;
private string mobile;
private Child[] myChildren; //mother "has a" many children
//props
public Child[] MyChildren
{
get { return myChildren; }
set { myChildren = value; }
}
public string Mobile
{
get { return mobile; }
set { mobile = value; }
}
public string LastName
{
get { return lastName; }
set { lastName = value; }
}
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
public int MotherId
{
get { return motherId; }
set { motherId = value; }
}
//constructors
//methods
//Get Mother Details
public override string ToString()
{
return motherId + ", " + firstName + ", " + lastName + ", " + mobile;
}
//AddChild
public bool AddChild(Child myChild)
{
for (int i = 0; i < myChildren.Length; i++)
{
if (myChildren[i] != null)
{
myChildren[i] = myChild;
return true;
}
}
return false;
}
//GetMyChildrenDetails
public string GetMyChildrenDetails()
{
string msg = "";
for (int i = 0; i < myChildren.Length; i++)
{
if (myChildren[i] != null)
{
msg += "\n" + myChildren[i];
}
}
return msg;
}
public class Child
{
//fields
private int childId;
private string firstName;
private string lastName;
private DateTime dateOfBirth;
private Mother myMother; //child "has a" mother
//props
public Mother MyMother
{
get { return myMother; }
set { myMother = value; }
}
public DateTime DateOfBirth
{
get { return dateOfBirth; }
set { dateOfBirth = value; }
}
public string LastName
{
get { return lastName; }
set { lastName = value; }
}
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
public int ChildId
{
get { return childId; }
set { childId = value; }
}
//constructors
//Child cannot be created without a mother
public Child(Mother myMother)
{
this.myMother = myMother;
}
//Child cannot be created without a mother
public Child(Mother myMother, int childId)
{
this.myMother = myMother;
this.childId = childId;
}
//methods
//Get Child Details
public override string ToString()
{
return childId + ", " + firstName + ", " + lastName + ", " + dateOfBirth;
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnRegister_Click(object sender, EventArgs e)
{
}
private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
}
private void closeToolStripMenuItem_Click(object sender, EventArgs e)
{
Close();
}
private void BtnAddChild_Click(object sender, EventArgs e)
{
Add_Child child = new Add_Child();
child.Show();
}
private void btnRegister_Click_1(object sender, EventArgs e)
{
//create a mother object
Mother m = new Mother();
m.MotherId = int.Parse(txtID.Text);
m.FirstName = txtFname.Text;
m.LastName = txtLname.Text;
m.Mobile = txtMobile.Text;
Giving the new child a reference to its parent object is not the cause of your issue. In summary, you state:
"to have values that will not show up in my label5.text "
This would indicate that it is either your binding that has an issue, you have not implemented INotifyPropertyChanged, or your UI updating mechanism is not working (if you are not using binding). As you haven't stated what you are using for the UI, that is about as much as I can help...
My suggestion, you may use List instead of array, because not all mothers have three children. Example code:
public static class Program
{
static void Main(string[] args)
{
Mother mother = new Mother {
FirstName = "M First", LastName = "M Last", Contact = "225632655"
};
//Add dependents
mother.AddChild(new Child{ChildID = 1, FirstName = "Child FirstName 1", LastName = "Child LastName 1"});
mother.AddChild(new Child{ChildID = 2, FirstName = "Child FirstName 2", LastName = "Child LastName 2"});
mother.AddChild(new Child{ChildID = 3, FirstName = "Child FirstName 3", LastName = "Child LastName 3"});
Console.WriteLine(mother);
//List all the mother dependents
foreach(Child c in mother.Children)
{
Console.WriteLine(c);
}
Console.ReadKey();
}
}
class Mother
{
public string FirstName {get; set;}
public string LastName {get; set;}
public string Contact {get; set;}
private List<Child> _child;
public Mother()
{
_child = new List<Child>();
}
public void AddChild(Child child)
{
_child.Add(child);
}
public List<Child> Children
{
get { return _child; }
}
public override string ToString()
{
return string.Format("{0}, {1} ({2})", LastName, FirstName, Contact);
}
}
class Child
{
public string FirstName {get; set;}
public string LastName {get; set;}
public int ChildID {get; set;}
public override string ToString()
{
return string.Format("{0} {1}, {2}", ChildID, LastName, FirstName);
}
}
I hope, this will help.

Categories

Resources