Why isn't my property doing the check? - c#

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;
}
}
}

Related

C# Using Custom class in a List

I have a class and I am using it inside a LIST
List<user> listWithCustomClass = List<user>();
myClass.cs
public class user
{
public user(string fullname, string city, string state, int age, int type)
{
name = fullname;
citi = city;
estate = state;
tipe = type;
}
private string name = string.Empty;
private string citi = string.Empty;
private string estate = string.Empty;
private int tipe = 0;
public string getFullname
{
get { return name; }
set { name = value;}
}
public string getCity
{
get { return citi; }
set { citi = value;}
}
public string getState
{
get { return state; }
set { state = value;}
}
public int getType
{
get { return type; }
set { type = value;}
}
}
How can I add a custom toString() without having to override generic toString(). I would like to add something like showDate().
For example, in a combobox I would like the output of the inserted information to be:
--> Hello, your name is {name} and your age is {age}
Like this:
foreach(var item in user)
{
user.ShowData();
}
Add this in your class:
public string ShowData()
{
return "Hello, your name is " + name + " and your age is " + age.ToString();
}
but you must also define age first. Which, following your style, would be:
private int age = 0;
and then in the constructor add:
this.age = age;
EDIT
foreach(var item in listWithCustomClass)
{
item.ShowData();
}

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

Can Derived class hide the accessors - Whats wrong with code below

I am trying to hide the accessors in derived class, is it valid? My system did not respond back on executing.
class BaseCS
{
private string name;
public string Name
{
get { return name; }
set { name = "Base " + value; }
}
}
class DerivedCS : BaseCS
{
public new string Name
{
set { Name = "Der " + value; }
get { return Name; }
}
}
public static void Main()
{
BaseCS one = new DerivedCS();
one.Name = "One";
Console.WriteLine("Name of object one is {0} ", one.Name);
((BaseCS)one).Name = "On1";
Console.WriteLine("Name of object one is {0} ", one.Name);
}
Shouldn't I expect output to be,
Name of object one is Base Der One
Name of object one is Base On1
This code:
public new string Name
{
set { Name = "Der " + value; }
get { return Name; }
}
Will lead to stack overflow, because Name in getters and setters will refer to Name in DerivedCS, not in BaseCS. Name property will call itself forever, until crashing. You need to use base.Name.
What you probably want is polymorphysm. You should make property virtual and override setter in the derived class.
If you do not use virtual properties, the following object will not behave the way you want:
BaseCS one = new DerivedCS();
one.Name = "name"; // base implementation is called
Changing property value in setter is usually a bad idea. Users expect the following contract to be followed:
var a = new A();
a.Foo = "bar";
Debig.Assert(a.Foo == "bar");
Here is what you should be doing
class BaseCS
{
private string name;
public virtual string Name
{
get { return name; }
set { name = "Base " + value; }
}
}
class DerivedCS : BaseCS
{
public override string Name
{
set { base.Name = "Der " + value; }
get { return base.Name; }
}
}
OR with a new keyword
class BaseCS
{
private string name;
public string Name
{
get { return name; }
set { name = "Base " + value; }
}
}
class DerivedCS : BaseCS
{
public new string Name
{
set { base.Name = "Der " + value; }
get { return base.Name; }
}
}
now you should create the object as the derived type to get your expected result
DerivedCS one = new DerivedCS();

issues calling another class

first class as follows:
public class employeeApp
{
public static void main()
{
EmployeeProgram.employee Employee = new EmployeeProgram.employee( );
}
public void employee(int employeeNumber, string name, string dateOfHire, int monthlySalary)
{
employeeNumber = 123;
name = Cody;
dateOfHire = 01/01/11;
monthlySalary = 2500;
}
}
second class as follows:
/*
* Mosbrucker_C_PRO_01 Author: Mosbrucker, Cody
* Creates a class for employee with data members;
* Employee number, name, date of hire, and monthly salary.
* ****************************************************/
public class employee
{
private int employeeNumber;
private string name;
private string dateOfHire;
private int monthlySalary;
public int EmployeeNumber
{
get
{
return employeeNumber;
}
set
{
employeeNumber = value;
}
}
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public string DateOfHire
{
get
{
return dateOfHire;
}
set
{
dateOfHire = value;
}
}
public int MonthlySalary
{
get
{
return monthlySalary;
}
set
{
monthlySalary = value;
}
}
public override string ToString()
{
return "Employee Id: " + employeeNumber +
"Employee Name: " + name +
"Employee Date of Hire: " + dateOfHire +
"Employee Monthly Salary: " + monthlySalary;
}
}
the problems I am getting are:
*In my employeeApp class "does not contain a "static" main method for suitable entry point"
*in my employeeApp class "the name Cody does not exist in current context
*in my employeeApp class relating to dateOfHire "cannot implicitly convert int to string
I'm doing this for a class and the assignment it:
Create a Employee class. Items to include as data members are employee number, name, date of hire, and monthly salary. Include appropriate constructors and properties. Override the ToString ( ) method to return all data members. Create a second class to test your Employee class.
Any help at all is greatly appreciated.
1.in C# we use Main(Capital M) so Main method should be :
static void Main()
2.You have to create the Constructor in your class employe
3.You have to assign String to the String variable but you are assigning date.
as below :
dateOfHire = 01/01/11;
in your constructor
4.Cody should be represented as String "Cody" in your Constructor
5.while assigning data to local variables in class use this to represent current object when assigning variable have same name
example : this.employeenumber=employeenumber;
file 1:
namespace employee
{
public class employeeApp
{
public static void Main()
{
EmployeeProgram.employee Employee = new EmployeeProgram.employee(123,"Cody","11/11/11",24567);//call your constructor
}
}
}
file 2:
/*
* Mosbrucker_C_PRO_01 Author: Mosbrucker, Cody
* Creates a class for employee with data members;
* Employee number, name, date of hire, and monthly salary.
* ****************************************************/
namespace EmployeeProgram
{
public class employee
{
private int employeeNumber;
private string name;
private string dateOfHire;
private int monthlySalary;
public employee(int employeeNumber, string name, string dateOfHire, int monthlySalary)
{
this.employeeNumber = 123;
this.name = "Cody";
this.dateOfHire = "01/01/11";
this.monthlySalary = 2500;
}
public int EmployeeNumber
{
get
{
return employeeNumber;
}
set
{
employeeNumber = value;
}
}
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public string DateOfHire
{
get
{
return dateOfHire;
}
set
{
dateOfHire = value;
}
}
public int MonthlySalary
{
get
{
return monthlySalary;
}
set
{
monthlySalary = value;
}
}
public override string ToString()
{
return "Employee Id: " + employeeNumber +
"Employee Name: " + name +
"Employee Date of Hire: " + dateOfHire +
"Employee Monthly Salary: " + monthlySalary;
}
}
}
Issue 1 - C# is case sensitive. Capitalize Main. The use of the public access modifier is not necessary and is generally not recommended for Main.
static void Main()
Issue 2 - For the second name = Cody; I guess you meant...name = "Cody";
Issue 3 - For the third issue you need to convert the int values to string by calling ToString() on int values. employeeNumber.ToString() and monthlySalary.ToString().
There are lots of issues here and they are all fairly basic. I recommend you use Google or explain why exactly you could not solve them. Otherwise it might appear you have not put forth the required effort to solve the problems yourself.
Issue 4 As for the I/O write problem you need to qualify using this keyword because of the naming conflict between your local variables and private fields:
public class employee
{
private int employeeNumber;
private string name;
private string dateOfHire;
private int monthlySalary;
public employee(int employeeNumber, string name, string dateOfHire, int monthlySalary)
{
this.employeeNumber = 123;//because you have naming collissions you need to use `this`
this.name = "Cody";
this.dateOfHire = "01 / 01 / 11";
this.monthlySalary = 2500;
}
public override string ToString()
{
return "Employee Id: " + employeeNumber +
"Employee Name: " + name +
"Employee Date of Hire: " + dateOfHire +
"Employee Monthly Salary: " + monthlySalary;
}
public void Print()
{
Console.WriteLine(this.ToString());
}
}
Then Main
static void Main(string[] args)
{
employee e = new employee(1,"","",0);//these values are ignored the way you set this up
e.Print();
Console.ReadLine();
}

C# Inconsistent accessibility error

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.

Categories

Resources