ArgumentOutOfRangeException. Use getter,setter - C# - c#

I need to create a class Person, that has fields:
name, surname and salary.
If the salary is lower than 0, I get the exception:
ArgumentOutOfRangeException. Use getter,setter
I tried with:
public class Employee
{
public string name { get; set; }
string surname { get; set; }
private int salary;
public int Salary
{
get
{
return salary;
}
set
{
if (salary < 0)
{
throw new ArgumentOutOfRangeException("salary", "wyplata ma byc wieksza niz 0");
}
else
{
salary = value;
}
}
}
}
in main:
Employee tmp = new Employee("michal", "jakowski", -1400);

In your code, when you check if (salary < 0), the field salary is not yet updated with value. So instead you need to check whether value is less than 0.
public int Salary
{
get
{
return salary;
}
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException("salary", "wyplata ma byc wieksza niz 0");
}
else
{
salary = value;
}
}
}

Related

Using keyword "value" in set accessor C#

I'm trying to use the keyword value in the set accessor and as long as the user entered value is greater than 0, I want to set it to the variable Quantity.
I can not seem to find what it is I am doing wrong. I keep getting a traceback error to for this Quantity = value;. Hoping someone can see what I don't. Thanks.
using System;
namespace Invoice
{
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine("How many parts would you like to " +
"enter into the system: ");
int newParts = int.Parse(Console.ReadLine());
Invoice[] invoice = new Invoice[newParts];
for (int i = 0; i < newParts; i++)
{
invoice[i] = new Invoice();
Console.WriteLine("Enter the part number: ");
invoice[i].PartNumber = Console.ReadLine();
Console.WriteLine("Enter description of item: ");
invoice[i].PartDescription = Console.ReadLine();
Console.WriteLine("Enter the quantity: ");
invoice[i].Quantity = int.Parse(Console.ReadLine());
Console.WriteLine("Enter in the price of the item: ");
invoice[i].PricePerItem = decimal.Parse(Console.ReadLine());
}
for (int i = 0; i < newParts; i++)
{
invoice[i].DisplayOrder();
}
}
}
}
using System;
namespace Invoice
{
public class Invoice
{
public string PartNumber { get; set; }
public string PartDescription { get; set; }
public int Quantity
{
get { return Quantity; }
set
{
if (value >= 0)
{
Quantity = value;
}
if (value <= 0)
{
Quantity = Quantity;
}
}
}
public decimal PricePerItem
{
get
{
return PricePerItem;
}
set
{
if(value >= 0.0m)
{
PricePerItem = value;
}
if (value <= 0.0m)
{
PricePerItem = PricePerItem;
}
}
}
public Invoice(String PartNumber, String PartDescription, int Quantity, decimal PricePerItem)
{
this.PartNumber = PartNumber;
this.PartDescription = PartDescription;
this.Quantity = Quantity;
this.PricePerItem = PricePerItem;
}
public Invoice()
{
}
public decimal GetInvoiceAmount(int numberOfItems, decimal priceOfItem)
{
return numberOfItems * priceOfItem;
}
public void DisplayOrder()
{
decimal total = GetInvoiceAmount(Quantity, PricePerItem);
// Display Receipt
Console.Write("\nOrder Receipt: ");
Console.WriteLine($"\nPart Number: {PartNumber}");
Console.WriteLine($"Unit Price: {PricePerItem:C}");
Console.WriteLine($"Quantity: {Quantity}");
Console.WriteLine($"Part Description: {PartDescription}");
Console.WriteLine($"Total price: {total:C}");
}
}
}
This makes no sense:
if (value >= 0)
{
Quantity = value;
}
if (value <= 0)
{
Quantity = Quantity;
}
Why would you set a property to itself? That can't achieve anything useful. You say that you want to set the property if and only if the assigned value is greater than zero, so why would you be checking value for anything but being greater than zero?
if (value > 0)
{
Quantity = value;
}
That's it, that's all.
That said, you also ought to be throwing an ArgumentOutOfRangeException if the value is not valid, rather than just silently not setting the property. The logical way to do that would be like so:
if (value <= 0)
{
throw new ArgumentOutOfRangeException(...);
}
Quantity = value;
Now the property value will only be set if an exception is not thrown.
I also just realised that you have no backing field for this property, so that's wrong. The whole thing should look like this:
private int quantity;
public int Quantity
{
get { return quantity; }
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(...);
}
quantity = value;
}
}
The error is because in your set {} you are invoking the same setter recursively.
private int quantity;
public int Quantity
{
get { return this.quantity; }
set
{
if (value >= 0)
{
this.quantity= value;
}
}
}
private decimal pricePerItem;
public decimal PricePerItem
{
get
{
return this.pricePerItem;
}
set
{
if(value >= 0.0m)
{
this.pricePerItem= value;
}
}
}

trying to calculate compute salary , compute deduction and compute net pay using abstract class in c#

abstract class
Salary is calculated by multiplying the daily rate by the numbers of days worked in a month.
im trying to calculate the salary which computes the salary of the employee and deduction which computes the deduction of the salary and net pay salary-deduction
for example: doctor=10000, teacher=20000, engineer=30000
trying to get the output
//
ID 001
Name J
Salary 15750.00
Deduction 3386.25
Net Pay 12363.75
namespace Practice
{
////////////////////////////////////////////
////////////////////////////////////////////
///////////// class employee ///////////////
////////////////////////////////////////////
////////////////////////////////////////////
abstract class Employee
{
int employeeid;
string name;
double salary, deduction, daysworked;
public Employee()
{
}
public int Employeeid
{
get { return employeeid; }
set { employeeid = value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
public double Daysworked
{
get { return daysworked; }
set { daysworked = value; }
}
public double Deduction
{
get { return deduction; }
set { deduction = value; }
}
public double Salary
{
get { return salary; }
set { salary = value; }
}
public virtual double calculatesalary()
{
return Salary * Daysworked;
}
public virtual double calulatededuction()
{
return calculatesalary() * Deduction;
}
}
////////////////////////////////////////////
////////////////////////////////////////////
///////////// class sample1 ///////////////
////////////////////////////////////////////
////////////////////////////////////////////
class sample1 : Employee
{
public sample1 (string name,int employeeid, double daysworked,double salary)
{
Name = name;
Employeeid = employeeid;
Daysworked = daysworked;
Salary = salary;
}
public override double calculatesalary()
{
if (calculatesalary() <= 10000)
{
Deduction = 0.11;
}
if (calculatesalary() >= 10001 && calculatesalary() <= 20000)
{
Deduction = 0.22;
}
if (calculatesalary() >= 20001 && calculatesalary() <= 30000)
{
Deduction = 0.34;
}
if (calculatesalary() >= 30001)
{
Deduction = 0.58;
}
return calculatesalary() * Deduction;
}
}
}
my question is where did i get it wrong ? :/
As John Wu pointed out, it ends up in an infinite loop since you invoke the calculatesalary() method in the sample1 class recursively. Using base.calculatesalary() will invoke the base method and then perform additional logic in the derived class. Modify your your method as follows:
public override double calculatesalary()
{
var salary = base.calculatesalary();
if (salary <= 10000)
{
Deduction = 0.11;
}
else if (salary >= 10001 && salary <= 20000)
{
Deduction = 0.22;
}
else if (salary >= 20001 && salary <= 30000)
{
Deduction = 0.34;
}
else if (salary >= 30001)
{
Deduction = 0.58;
}
return salary * Deduction;
}
Please consider refactoring this class since it requires some fixes as Dan Chase mentioned.

How to Create a simple atm program in c# using inheritance

I'm trying to create an e-ATM console app using C# using inheritance, but every time I debug I see that the derived class values are null, whereas the base class fields or properties are filled with values. Why is the derived class not showing the list with their data even after it is inherited from the base class?
class CreateAccount
{
string firstName, lastName, dateOfBirth, phoneNO, fathersName, mothersName;
double initialBalance; int pinNo = 100, accountNo = 1234, age; DateTime yearOfBirth;
protected static List<CreateAccount> data = new List<CreateAccount>();
protected string FirstName
{
get { return this.firstName; }
set
{
if (string.IsNullOrEmpty(value)) throw new Exception();
else firstName = value;
}
}
protected string LastName
{
get { return this.lastName; }
set
{
if (string.IsNullOrEmpty(value)) throw new Exception();
else lastName = value;
}
}
protected string DateOfBirth
{
get { return this.dateOfBirth; }
set
{
if (string.IsNullOrEmpty(value)) throw new Exception();
else dateOfBirth = value;
}
}
protected string PhoneNo
{
get { return this.phoneNO; }
set
{
if ((string.IsNullOrEmpty(value)) || value.Length != 10)
throw new Exception();
else
phoneNO = value;
}
}
protected string FathersName
{
get { return this.fathersName; }
set
{
if (string.IsNullOrEmpty(value))
throw new Exception();
else
fathersName = value;
}
}
protected string MothersName
{
get { return this.mothersName; }
set
{
if (string.IsNullOrEmpty(value))
throw new Exception();
else
mothersName = value;
}
}
protected double InititailBalance
{
get { return this.initialBalance; }
set
{
if (double.IsNaN(value))
throw new Exception();
else
initialBalance = value;
}
}
protected int PinNo
{
get { return this.pinNo; }
}
protected int AccountNo
{
get { return this.accountNo; }
}
public void GenerateAccount()
{
// code for asking user for their details.
data.Add(this);
}
}
class ATM :CreateAccount
{
public void Deposit()
{
Console.WriteLine("Enter your account number");
int accountNo = int.Parse(Console.ReadLine());
if (accountNo == AccountNo)
{
Console.WriteLine("Enter your amount you wish to deposit");
int amount = int.Parse(Console.ReadLine());
InititailBalance+= amount;
}
}
}
class Program
{
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("Menu");
Console.WriteLine("1.Create Account");
Console.WriteLine("2.ATM");
Console.Write("Please enter your selections: ");
int select = int.Parse(Console.ReadLine());
switch (select)
{
case 1:
CreateAccount account = new CreateAccount();
account.GenerateAccount();
break;
case 2:
ATM atm = new ATM();
atm.Deposit();
break;
}
}
}
}
You are creating two different objects: a 'CreateAccount' Object and an 'ATM' object.
An ATM object does not automatically inherit the values from a previously created CreateAccount object, they are two completely different, unrelated entities.
So for your ATM object to have the same values that your CreateAccount object has, you would have to copy the CreateAccount object to your ATM object.
CreateAccount account = new CreateAccount();
//set account variables here
ATM atm = (ATM)account;
Here is how it's done with proper use of inheritance which is useless in this case actually. Dictionary is the proper datastructure to use in this case because you can avoid duplicates with it. Also from this code you might want to remove the accountNo from Account class to avoid duplicate numbers being kept and the ask it beffore calling GenerateAccount() method. So this is full console app:
using System;
using System.Collections.Generic;
using System.Linq;
namespace ATM
{
class Account
{
string firstName, lastName, dateOfBirth, phoneNO, fathersName, mothersName;
double initialBalance;
int pinNo, accountNo, age;
DateTime yearOfBirth;
public Account()
{
pinNo = 100;
accountNo = 1234;
}
public string FirstName
{
get { return this.firstName; }
set
{
if (string.IsNullOrEmpty(value)) throw new Exception();
else firstName = value;
}
}
public string LastName
{
get { return this.lastName; }
set
{
if (string.IsNullOrEmpty(value)) throw new Exception();
else lastName = value;
}
}
public string DateOfBirth
{
get { return this.dateOfBirth; }
set
{
if (string.IsNullOrEmpty(value)) throw new Exception();
else dateOfBirth = value;
}
}
public string PhoneNo
{
get { return this.phoneNO; }
set
{
if ((string.IsNullOrEmpty(value)) || value.Length != 10)
throw new Exception();
else
phoneNO = value;
}
}
public string FathersName
{
get { return this.fathersName; }
set
{
if (string.IsNullOrEmpty(value))
throw new Exception();
else
fathersName = value;
}
}
public string MothersName
{
get { return this.mothersName; }
set
{
if (string.IsNullOrEmpty(value))
throw new Exception();
else
mothersName = value;
}
}
public double InititailBalance
{
get { return this.initialBalance; }
set
{
if (double.IsNaN(value))
throw new Exception();
else
initialBalance = value;
}
}
public int PinNo
{
get { return this.pinNo; }
}
public int AccountNo
{
get { return this.accountNo; }
}
public void GenerateAccount()
{
// code for asking user for their details.
}
}
class ATM
{
public static Dictionary<int, Account> AccountsList;
static ATM()
{
AccountsList = new Dictionary<int, Account>();
}
public void CreateAccount()
{
Account acc = new Account();
acc.GenerateAccount();
AccountsList.Add(acc.AccountNo, acc);
}
public void Deposit()
{
Console.WriteLine("Enter your account number");
int accountNo = int.Parse(Console.ReadLine());
if (AccountsList.ContainsKey(accountNo))
{
Console.WriteLine("Enter your amount you wish to deposit");
int amount = int.Parse(Console.ReadLine());
AccountsList[accountNo].InititailBalance += amount;
}
}
}
class Program
{
static void Main(string[] args)
{
ATM atm = new ATM();
while (true)
{
Console.WriteLine("Menu");
Console.WriteLine("1.Create Account");
Console.WriteLine("2.ATM");
Console.Write("Please enter your selections: ");
int select = int.Parse(Console.ReadLine());
switch (select)
{
case 1:
atm.CreateAccount();
break;
case 2:
atm.Deposit();
break;
default:
Console.WriteLine("Invalid selection!");
break;
}
}
}
}
}
CreateAccount is an operation of Atm and this is why I don't think you should be using inheritance. I propose this solution:
Class Account:
class Account
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
public string PhoneNumber { get; set; }
public double Balance { get; set; }
// More properties here
...
}
Class Atm:
class Atm
{
public List<Account> Accounts { get; set; }
public Atm()
{
Accounts = new List<Account>();
}
public void CreateAccount()
{
var account = new Account();
// Get details from user here:
...
account.Balance = 0.0;
account.Id = Accounts.Count + 1;
Accounts.Add(account);
}
public void Deposit()
{
int accountId;
// Get input from the user here:
// --------------------------------
// 1. Check that the account exists
// 2. Deposit into the account.
...
}
Full example:
class Program
{
static void Main()
{
var atm = new Atm();
while (true)
{
int option;
Console.WriteLine();
Console.WriteLine("Menu:");
Console.WriteLine("1. Create Account");
Console.WriteLine("2. Deposit");
Console.WriteLine();
Console.Write("Please make a selection: ");
var input = int.TryParse(Console.ReadLine(), out option);
Console.WriteLine("-----------------");
switch (option)
{
case 1:
atm.CreateAccount();
break;
case 2:
atm.Deposit();
break;
}
}
}
}
class Account
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
public string PhoneNumber { get; set; }
public double Balance { get; set; }
}
class Atm
{
public List<Account> Accounts { get; set; }
public Atm()
{
Accounts = new List<Account>();
}
public void CreateAccount()
{
var account = new Account();
Console.WriteLine("Create a new account!");
Console.WriteLine();
Console.Write("Enter first name: ");
account.FirstName = Console.ReadLine();
Console.Write("Enter last name: ");
account.LastName = Console.ReadLine();
Console.Write("Enter date of birth: ");
account.DateOfBirth = DateTime.Parse(Console.ReadLine());
Console.Write("Enter phone number: ");
account.PhoneNumber = Console.ReadLine();
account.Balance = 0.0;
account.Id = Accounts.Count + 1;
Accounts.Add(account);
}
public void Deposit()
{
int accountId;
Console.Write("Enter your account number: ");
int.TryParse(Console.ReadLine(), out accountId);
var account = Accounts.FirstOrDefault(a => a.Id == accountId);
if (account != null)
{
double amount;
Console.Write("Enter amount to deposit: ");
double.TryParse(Console.ReadLine(), out amount);
account.Balance += amount;
Console.Write("Your new balance is {0}", account.Balance);
}
else
{
Console.WriteLine("That account does not exist!");
}
}
}

C# label is not displaying correctly

I'm creating a registration app where you can enter the student name, id and gpa and it will all be stored in a collection list. The label is showing as 0 even when students are registered. Here is the relevant code. Any help is appreciated.
namespace Lab09
{
class Student
{
string name;
int id;
int intNumber;
decimal gpa;
public Student(string Name, int Id, decimal Gpa)
{
name = Name;
id = Id;
gpa = Gpa;
}
public string Name
{
set { name = value; }
get
{
return name;
}
}
public int Id
{
get
{
return id;
}
}
public decimal Gpa
{
get
{
return gpa;
}
}
public int Number
{
get
{
return intNumber;
}
}
}
}
namespace Lab09
{
public partial class Form1 : Form
{
List<Student> listofStudents;
int intCurrentStudent = 0;
public Form1()
{
InitializeComponent();
listofStudents = new List<Student>();
}
private void btnRegister_Click(object sender, EventArgs e)
{
try
{
if (Decimal.Parse(txtGPA.Text) > 0 && Decimal.Parse(txtGPA.Text) <= 4)
{
if (txtName.Text != "")
{
listofStudents.Add(new Student(txtName.Text, Int32.Parse(txtID.Text), Decimal.Parse(txtGPA.Text)));
intCurrentStudent = listofStudents.Count - 1;
txtName.Enabled = false;
txtID.Enabled = false;
txtGPA.Enabled = false;
btnRegister.Enabled = false;
if (listofStudents.Count > 1)
{
btnPrevious.Enabled = true;
}
displayNumStudents();
}
}
else
{
MessageBox.Show("You must enter a name and GPA must be above 0 and less than or equal to 4");
}
}
catch
{
MessageBox.Show("ID and GPA need to be numbers");
}
}
private void displayNumStudents()
{
int NumOfStudents = 0;
foreach (Student aStudent in listofStudents)
{
NumOfStudents += aStudent.Number;
}
lblNum.Text = NumOfStudents.ToString();
}
you have field int intNumber that your Number property is returning, but you aren't ever setting it. And then you're using that number to count your students, which doesn't make sense.
I assume you want the registered student count:
private void displayNumStudents()
{
int NumOfStudents = listOfStudents.Count();
lblNum.Text = NumOfStudents.ToString();
}
The variable intNumber;
In your student class is never assigned and only returned via the Number property in your Student class.
public int Number
{
get
{
return intNumber;
}
}
You need to update this property when a new Student is added to the collection.
You could modify your Student constructor to take in this argument and assign it there:
public Student(string Name, int Id, decimal Gpa, int studentNumber)
{
name = Name;
id = Id;
gpa = Gpa;
intNumber = studentNumber;
}
You would then have to pass this to the new Student object when you create it and then add it to the list, for example:
string name = txtName.Text;
int id = Int32.Parse(txtID.Text);
decimal gpa = decimal.Parse(txtGPA.Text);
int studentNumber = listofStudents.Count() + 1;
Student student = new Student(name, id, gpa, studentNumber);
listofStudents.Add(student);

C# .Net 3.5 Using Overloaded Indexers with different return types

I have a parent class which is essentially a glorified list. It's extended by several subclasses for various functionalities.
public class HierarchialItemList<ItemType> : IEnumerable<ItemType>
{
public ItemType this[String itemCode]
{
get
{
foreach (IHierarchialItem curItem in hierarchialItems)
{
if (curItem.Code.Equals(itemCode, StringComparison.CurrentCultureIgnoreCase))
{
return ((ItemType)curItem);
}
}
return (default(ItemType));
}
}
public ItemType this[Int32 index]
{
get
{
return (hierarchialItems[index]);
}
}
}
public class DatabaseList : HierarchialItemList<Database>
{
public DatabaseList this[CommonDatabaseType typeToFilter]
{
get
{
DatabaseList returnList = new DatabaseList();
foreach(Database curDatabase in this)
{
if (curDatabase.DatabaseType.Equals(typeToFilter))
{
returnList.Add(curDatabase);
}
}
return (returnList);
}
}
public DatabaseList this[Environments.RMSEnvironment environmentToFilter]
{
get
{
DatabaseList returnList = new DatabaseList();
foreach(Database curDatabase in this)
{
if (curDatabase.ParentEnvironment.Equals(environmentToFilter))
{
returnList.Add(curDatabase);
}
}
return (returnList);
}
}
}
The problem is that C# thinks that this:
Database testDatabase = sampleDatabaseList[0];
Is an error and that the indexer should be returning a DatabaseList, not a Database. You and I both know that's false. Any workarounds or do all indexers have to have the same return type?
Edit: I just figured out that it's because of using an enumeration as an indexer which is internally an integer. Still, any way to use both an enumeration and an integer?
Edit 2: As requested, here is some compiliable test code which demonstrates the problem.
using System;
using System.Collections.Generic;
namespace CSQT
{
class A<T>
{
List<T> temp;
public A()
{
temp = new List<T>();
}
public void AddItem(T itemToAdd)
{
temp.Add(itemToAdd);
}
public T this[String code]
{
get { return (temp[0]); }
}
public T this[Int32 index]
{
get { return (temp[index]); }
}
}
class B : A<String>
{
public B()
: base()
{
}
public B this[BTypes testType]
{
get
{
return (this);
}
}
}
enum BTypes { TEMP1, TEMP2 };
class C
{
public C()
{
B temp = new B();
//Compile error: Cannot implicitly convert type 'CSQT.B' to 'string'
String temp2 = temp[0];
//Compile error: Cannot convert type 'CSQT.B' to 'string'
String temp3 = (String)temp[0];
//This compiles and runs but instead of going to A.this[int32], it goes to B.this[BTypes testType]
B temp4 = temp[0];
}
}
}
Why do we know that to be false? The line
Database testDatabase = sampleDatabaseList[0];
invokes the indexer with the parameter 0 which is a int literal and therefore, seeing that DatabaseList inherits from HierarchialItemList<Database> will invoke the indexer defined by
public ItemType this[Int32 itemCode] { get; }
which is declared to return an ItemType. You haven't told us what ItemType is. We have no reason to know that an ItemType can be assigned to a variable of type Database.
Indexers do not have to return the same type. However, it is not possible to overload solely on the basis of return type. That is, this is legal
class IndexerTest {
public int this[int index] {
get {
return 0;
}
}
public string this[double index] {
get {
return "Hello, success!";
}
}
}
This is not
class IndexerTest {
public int this[int index] {
get {
return 0;
}
}
public string this[int index] {
get {
return "Hello, fail!";
}
}
}
Responding to your edit:
Edit: I just figured out that it's because of using an enumeration as an indexer which is internally an integer. Still, any way to use both an enumeration and an integer?
If you want to invoke the indexer that accepts an enum, invoke it like so:
sampleDatabaseList[Environments.RMSEnvironment.SomeEnumValue];
This is perfectly valid code.
class SomeClass { }
public class A<T> : IEnumerable<T>
{
public T this[int index]
{
get
{
return (this[index]);
}
}
public T this[String index]
{
get
{
return (this[index]);
}
}
}
public class B : A<SomeClass>
{
public B this[char typeToFilter]
{
get
{
return new B();
}
}
}
B classList = new B();
SomeClass test = classList[0];
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestNameSpace
{
public class Employee : Person
{
string id;
public string Id
{
get { return id; }
set { id = value; }
}
decimal salary;
public decimal Salary
{
get { return salary; }
set { salary = value; }
}
string password;
public string Password
{
set { password = value; }
}
int ichk = 1, schk = 1, pchk = 1;
public Employee()
: base()
{
Id = null;
Salary = Convert.ToDecimal("0.0");
Password = null;
}
public Employee(string n, char g, DateTime d, string empid, decimal sal, string pwd)
: base(n, g, d)
{
Id = empid;
Salary = sal;
Password = pwd;
}
public override void Accept()
{
base.Accept();
try
{
Console.Write("Enter the EMPID:");
Id = Console.ReadLine();
if (string.IsNullOrEmpty(Id) == true)
{
ichk = 0;
Console.WriteLine("No ID entered!");
}
string salcheck;
Console.Write("Enter the Salary:");
salcheck = Console.ReadLine();
if (string.IsNullOrEmpty(salcheck) == true)
{
schk = 0;
Console.WriteLine("Invalid Salary");
}
else
{
Salary = Convert.ToDecimal(salcheck);
if (Salary < 0)
{
schk = 0;
Console.WriteLine("Invalid Salary");
}
}
Console.Write("Enter Password:");
Password = Console.ReadLine();
if (string.IsNullOrEmpty(password) == true)
{
pchk = 0;
Console.WriteLine("Empty Password!");
}
else
{
string pwd;
int pchk = 0;
do
{
Console.Write("Re-Enter Password:");
pwd = Console.ReadLine();
if (string.IsNullOrEmpty(pwd) == true || pwd != password)
Console.WriteLine("Passwords don't match!");
else
pchk = 1;
} while (pchk == 0);
}
}
catch (Exception e)
{
Console.Write(e.Message);
}
}
public override void Print()
{
base.Print();
if (ichk == 1)
{
Console.WriteLine("EMPID:{0}", Id);
}
else
Console.WriteLine("No Id!");
if (schk == 1)
{
Console.WriteLine("Salary:{0}", Salary);
}
else
Console.WriteLine("Invalid Salary!");
}
}
}
------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestNameSpace
{
public class Person
{
protected string name;
public string Name
{
get { return name; }
set { name = value; }
}
protected char gender;
public char Gender
{
get { return gender; }
set { gender = value; }
}
protected DateTime? dob;
public DateTime? Dob
{
get { return dob; }
set { dob = value; }
}
protected int age;
public int Age
{
get { return age; }
}
public Person()
{
Name = "Default";
Gender = 'M';
Dob = null;
age = 0;
}
public Person(string n, char g, DateTime d)
{
Name = n;
Gender = g;
Dob = d;
age = DateTime.Now.Year - Dob.Value.Year;
}
int nchk = 1, gchk = 0, dchk = 0;
string datetimecheck, gendercheck;
public virtual void Accept()
{
try
{
Console.Write("Enter the name:");
Name = Console.ReadLine();
if (string.IsNullOrEmpty(Name)==true)
{
nchk = 0;
Console.WriteLine("No name entered!");
}
Console.Write("Enter the Date of birth:");
datetimecheck = Console.ReadLine();
if (string.IsNullOrEmpty(datetimecheck) == true)
{
dchk = 0;
Console.WriteLine("No date entered!");
}
else
{
Dob = Convert.ToDateTime(datetimecheck);
age = DateTime.Now.Year - Dob.Value.Year;
dchk = 1;
}
Console.Write("Enter Gender:");
gendercheck = Console.ReadLine();
if (gendercheck != "m" && gendercheck != "M" && gendercheck != "f" && gendercheck != "F")
{
gchk = 0;
Console.WriteLine("Invalid Gender");
}
else
{
gchk = 1;
Gender = Convert.ToChar(gendercheck);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
public virtual void Print()
{
Console.WriteLine("\n\nThe Employee Details are:\n");
if (nchk == 1)
{
Console.WriteLine("Name:{0}", Name);
}
else
Console.WriteLine("No Name!");
if (gchk == 1)
{
Console.WriteLine("Gender:{0}", Gender);
}
else
Console.WriteLine("No Gender!");
if (dchk == 1)
{
Console.WriteLine("Date Of Birth:{0}", Dob);
Console.WriteLine("Age:{0}", Age);
}
else
Console.WriteLine("No Date Of Birth!");
}
}
}
After adding the necessary classes and attributes to get your code sample to compile, I was able to run this statement with no issues:
Database testDatabase = sampleDatabaseList[0];
If you're getting an error that sampleDatabaseList[0] returns a DatabaseList, please provide a compilable code sample that contains the statement DatabaseList testDatabase = sampleDatabaseList[0];
---TRIGGER--
CREATE TRIGGER TriggerTest
ON EMP
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
declare #day varchar(10)
select #day=datename(dw,getdate())
declare #hour int
Select #hour=convert(varchar(2),getdate(),114)
if ( #hour < 9 OR #hour > 13 OR #day = 'Saturday' OR #day = 'Sunday')
BEGIN
if UPDATE(EMPID)
RAISERROR ('Error!',1,16)
rollback tran
END
END
Insert into EMP values(1003,'A','A')
drop trigger TriggerTest
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestNameSpace
{
public class Employee:Person
{
string id;
public string Id
{
get { return id; }
set { id = value; }
}
decimal salary;
public decimal Salary
{
get { return salary; }
set { salary = value; }
}
string password;
public string Password
{
set { password = value; }
}
int ichk = 1, schk = 1, pchk = 1;
public Employee()
: base()
{
Id = null;
Salary = Convert.ToDecimal("0.0");
Password = null;
}
public Employee(string n, char g, DateTime d, string empid, decimal sal, string pwd)
: base(n, g, d)
{
Id = empid;
Salary = sal;
Password = pwd;
}
public override void Accept()
{
base.Accept();
try
{
Console.Write("Enter the EMPID:");
Id = Console.ReadLine();
if (Id == null)
{
ichk = 0;
Console.WriteLine("No ID entered!");
}
Console.Write("Enter the Salary:");
Salary = Convert.ToDecimal(Console.ReadLine());
if (Salary < 0)
{
schk = 0;
Console.WriteLine("Invalid Salary");
}
Console.Write("Enter Password:");
Password = Convert.ToString(Console.ReadLine());
if (password == null)
{
pchk = 0;
Console.WriteLine("Empty Password!");
}
}
catch (Exception e)
{
Console.Write(e.Message);
}
}
public override void Print()
{
base.Print();
if (ichk == 1)
{
Console.WriteLine("EMPID:{0}", Id);
}
else
Console.WriteLine("No Id!");
if (schk == 1)
{
Console.WriteLine("Salary:{0}", Salary);
}
else
Console.WriteLine("Invalid Salary!");
}
}
}
-----PERSON-----
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestNameSpace
{
public class Person
{
protected string name;
public string Name
{
get { return name; }
set { name = value; }
}
protected char gender;
public char Gender
{
get { return gender; }
set { gender = value; }
}
protected DateTime dob;
public DateTime Dob
{
get { return dob; }
set { dob = value; }
}
protected int age;
public int Age
{
get { return age; }
}
public Person()
{
Name = "Default";
Gender = 'M';
Dob = Convert.ToDateTime("09 / 12 / 1990");
age = 0;
}
public Person(string n, char g, DateTime d)
{
Name = n;
Gender = g;
Dob = d;
age = DateTime.Now.Year - Dob.Year;
}
int nchk = 1, gchk = 1, dchk = 1;
public virtual void Accept()
{
try
{
Console.Write("Enter the name:");
Name = Console.ReadLine();
if(Name == null)
{
nchk = 0;
Console.WriteLine("No name entered!");
}
Console.Write("Enter the Date of birth:");
Dob = Convert.ToDateTime(Console.ReadLine());
if (Dob == null)
{
dchk = 0;
Console.WriteLine("No date entered!");
}
else
{
age = DateTime.Now.Year - Dob.Year;
}
Console.Write("Enter Gender:");
Gender = Convert.ToChar(Console.ReadLine());
if (Gender != 'm' && Gender != 'M' && Gender != 'F' && Gender != 'f')
{
gchk = 0;
Console.WriteLine("Invalid Gender");
}
}
catch (Exception e)
{
Console.Write(e.Message);
}
}
public virtual void Print()
{
Console.WriteLine("\n\nThe Employee Details are:\n");
if (nchk == 1)
{
Console.WriteLine("Name:{0}", Name);
}
else
Console.WriteLine("No Name!");
if (gchk == 1)
{
Console.WriteLine("Gender:{0}", Gender);
}
else
Console.WriteLine("No Gender!");
if (dchk == 1)
{
Console.WriteLine("Date Of Birth:{0}", Dob);
Console.WriteLine("Age:{0}", Age);
}
else
Console.WriteLine("No Date Of Birth!");
}
}
}

Categories