I have a simple inventory application which is a program which you can add, view and delete the product. Currently I had already finished the add function and view function but left only the delete function which I am unsure of. ( Main program case 3)
class Inventory
{
Product []items;
int maxSize;
int size;
public Inventory(int in_maxSize)
{
maxSize = in_maxSize;
size = 0;
items = new Product[maxSize];
}
public bool AddProduct(Product in_Product)
{
if(getSize()<maxSize)
{
items[size] = in_Product;
size++;
return true;
}
else
{
return false;
}
}
public int getSize()
{
return size;
}
public Product getProduct(int index)
{
return items[index];
}
}
}
here is my product class:
class Product
{
private string name;
private int itemNumber;
private int unitsInStock;
private double price;
private double value;
public Product()
{
}
public Product(string in_name, int in_itemNumber, int in_unitsInStock, double in_price)
{
name = in_name;
itemNumber = in_itemNumber;
unitsInStock = in_unitsInStock;
price = in_price;
}
public double getValueOfInventory()
{
value = unitsInStock * price;
return this.value;
}
public int getItemNumber()
{
return this.itemNumber;
}
public string getName()
{
return this.name;
}
public int getUnitsInStock()
{
return this.unitsInStock;
}
public double getPrice()
{
return this.price;
}
public void setItemNumber(int in_itemNumber)
{
itemNumber = in_itemNumber;
}
public void setName(string in_name)
{
name = in_name;
}
public void setUnitsInStock(int in_unitsInStock)
{
unitsInStock = in_unitsInStock;
}
public void setPrice(double in_price)
{
price = in_price;
}
}
}
Here is my main program:
class Program
{
static void Main(string[] args)
{
Inventory myInventory = new Inventory(100);
Product myProduct = new Product();
myProduct.setItemNumber(1000);
myProduct.setName("Pen");
myProduct.setPrice(1.25);
myProduct.setUnitsInStock(50);
myInventory.AddProduct(myProduct);
Product myProduct1 = new Product("Paper", 2000, 5000, 12.85);
myInventory.AddProduct(myProduct1);
Product tempProduct;
int x = 0;
do
{
Console.WriteLine("1.Add product");
Console.WriteLine("2.View product");
Console.WriteLine("3.Delete product");
Console.WriteLine("4.Exit the Application");
Console.WriteLine("------------------");
x = Convert.ToInt32(Console.ReadLine());
switch (x)
{
case 1:
Console.Write("Item number\t\t:");
int a=Convert.ToInt32(Console.ReadLine());
Console.Write("Name\t\t\t:");
string b=Convert.ToString(Console.ReadLine());
Console.Write("Price\t\t\t:");
double c=Convert.ToDouble(Console.ReadLine());
Console.Write("Units in stocks\t\t:");
int d=Convert.ToInt32(Console.ReadLine());
Product myProduct2 = new Product(b,a,d,c);
myInventory.AddProduct(myProduct2);
// Product myProduct1 = new Product("Paper", 2000, 5000, 12.85);
// myInventory.AddProduct(myProduct1);
/*Console.Write("Item number\t\t:");
ItemNo = Convert.ToInt32(Console.ReadLine());
Console.Write("Name\t\t\t:");
Name = Convert.ToString(Console.ReadLine());
Console.Write("Price\t\t\t:");
Price = Convert.ToDouble(Console.ReadLine());
Console.Write("Units in stocks\t\t:");
UnitsInStocks = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("------------------");*/
break;
case 2:
for (int i = 0; i < myInventory.getSize(); i++)
{
tempProduct = myInventory.getProduct(i);
Console.WriteLine("Item number\t\t:" + tempProduct.getItemNumber());
Console.WriteLine("Name\t\t\t:" + tempProduct.getName());
Console.WriteLine("Price\t\t\t:" + tempProduct.getPrice());
Console.WriteLine("Units in stocks\t\t:" + tempProduct.getUnitsInStock());
Console.WriteLine("------------------");
}
break;
case 3:
int j;
Console.WriteLine("Please enter the item id for the items that you want to delete");
j = Convert.ToInt32(Console.ReadLine());
if (j == a)
{
break;
case 4:
Environment.Exit(0);
break;
default:
break;
}
}
while (x != 4);
}
}
}
In my main program, i left case 3 undone as that is the delete function part,
How can I accomplish this?
This is the simple way. Replace your array with a List of products:
class Inventory
{
List<Product> items;
int maxSize;
public Inventory(int in_maxSize)
{
maxSize = in_maxSize;
items = new List<Product>();
}
public bool AddProduct(Product in_Product)
{
if(items.Count < maxSize)
{
items.Add(in_Product);
return true;
}
else
{
return false;
}
}
public Product getProduct(int index)
{
return items[index];
}
public void removeProduct(int index)
{
items.removeAt(index);
}
}
In your switch call removeProduct method to delete the product at position that you pass.
Related
I have a problem. I try compare two list currentItemsInColl and bPList. Inside bPList i have other list RequiredItems and now is what I need.
I want compare currentItemsInColl and RequiredItems and return bPList.craftingBlueprint.
I try Compare but I dont know how use it :/
using Devdog.InventoryPro;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CraftingAutoUpdate : MonoBehaviour {
public ItemCollectionBase itemCollection;
public ItemCollectionBase rewardCollection;
public CraftingCategory craftingCategory;
[Header("Blue Print List")]
public List<BlueprintList> bPList = new List<BlueprintList>();
public List<CurrentItemInCollList> currentItemsInColl = new List<CurrentItemInCollList>();
private CraftingBlueprint readyBlueprint;
public void OnShow()
{
GetBluePrint();
InvokeRepeating("StartUpdate",0f,0.05f);
}
public void OnHide()
{
CancelInvoke("StartUpdate");
}
private void StartUpdate()
{
UpdateDirectory();
UpdateFindMatchItems();
UpdateCraftResults();
}
private void GetBluePrint()
{
bPList.Clear();
foreach (var b in craftingCategory.blueprints)
{
if (b != null)
{
var rI = b.requiredItems;
var listReqItems = new List<RequiredItem>();
foreach (var e in rI)
{
listReqItems.Add(new RequiredItem(e.item.ID, e.amount));
}
bPList.Add(new BlueprintList(b.name, b, listReqItems));
}
}
}
private void UpdateDirectory()
{
currentItemsInColl.Clear();
foreach(var item in itemCollection)
{
if (item.item != null)
{
var cT = item.item.ID;
if (currentItemsInColl.Find(u =>u.itemID == cT) == null)
{
var itemCount = itemCollection.GetItemCount(item.item.ID);
currentItemsInColl.Add(new CurrentItemInCollList(item.item.ID, itemCount));
}
}
}
}
In this methode I try find same items in collections:
private void UpdateFindMatchItems()
{
readyBlueprint = null;
bool matchFailed = false;
int requiredItemCount = 0;
int currentItemsInCollCount = currentItemsInColl.Count;
foreach(var bp in bPList)
{
requiredItemCount = bp.RequiredItems.Count;
foreach(var rI in bp.RequiredItems)
{
if(CompareLists(currentItemsInColl, bp.RequiredItems))
{
print("aa");
}
print(currentItemsInCollCount);
}
}
private void UpdateCraftResults()
{
rewardCollection.Clear();
if (readyBlueprint != null)
{
foreach (var items in readyBlueprint.resultItems)
{
rewardCollection.AddItem(items.item,null,true,false);
}
}
}
I try somthing like this but is wont work with this lists:
public static bool CompareLists<T>(List<T> aListA, List<T> aListB)
{
if (aListA == null || aListB == null || aListA.Count != aListB.Count)
return false;
if (aListA.Count == 0)
return true;
Dictionary<T,T> lookUp = new Dictionary<T,T>();
// create index for the first list
for (int i = 0; i < aListA.Count; i++)
{
uint count = 0;
if (!lookUp.TryGetValue(aListA[i], out count))
{
lookUp.Add(aListA[i], 1);
continue;
}
lookUp[aListA[i]] = count + 1;
}
for (int i = 0; i < aListB.Count; i++)
{
uint count = 0;
if (!lookUp.TryGetValue(aListB[i], out count))
{
// early exit as the current value in B doesn't exist in the lookUp (and not in ListA)
return false;
}
count--;
if (count <= 0)
lookUp.Remove(aListB[i]);
else
lookUp[aListB[i]] = count;
}
// if there are remaining elements in the lookUp, that means ListA contains elements that do not exist in ListB
return lookUp.Count == 0;
}
}
And this is my lists:
/* LISTS */
[Serializable]
public class CurrentItemInCollList
{
public uint itemID;
public uint itemAmount;
public CurrentItemInCollList(uint newitemID, uint newItemAmount)
{
itemID = newitemID;
itemAmount = newItemAmount;
}
}
[Serializable]
public class BlueprintList
{
public string bluePrintName;
public CraftingBlueprint craftingBlueprint;
public List<RequiredItem> RequiredItems = new List<RequiredItem>();
public BlueprintList(string newBluePrintName, CraftingBlueprint newcraftingBlueprint, List<RequiredItem> list)
{
bluePrintName = newBluePrintName;
craftingBlueprint = newcraftingBlueprint;
RequiredItems = list;
}
}
[Serializable]
public class RequiredItem
{
public uint itemID;
public uint itemAmount;
public RequiredItem( uint newitemID, uint newItemAmount)
{
itemID = newitemID;
itemAmount = newItemAmount;
}
}
I forgot.. CurrentItemInCollList.itemAmount can be >= RequiredItems.itemAmount
Dictionary use hash values to compare objects.
The stored classes must implement public override int GetHashCode(){}
Use Linq - here is a small console example:
class Program
{
static void Main(string[] args)
{
//Required list
List<Order> currentItemsInColl = new List<Order>();
currentItemsInColl.Add(new Order() { Name = "bike1", Id = "01" });
currentItemsInColl.Add(new Order() { Name = "bike4", Id = "04" });
//List of all items
List<BPP> bPList = new List<BPP>();
bPList.Add(new BPP() { BikeName = "bike1", Idzzz = "01" });
bPList.Add(new BPP() { BikeName = "bike2", Idzzz = "02" });
bPList.Add(new BPP() { BikeName = "bike3", Idzzz = "03" });
bPList.Add(new BPP() { BikeName = "bike4", Idzzz = "04" });
bPList.Add(new BPP() { BikeName = "bike5", Idzzz = "05" });
//Blueprint List
List<BPP> Blueprint = new List<BPP>();
//get all items into the Blueprint list
foreach (Order i in currentItemsInColl)
{
List<BPP> tmp = bPList.FindAll(x => x.Idzzz.Contains(i.Id));
//here you add them all to a list
foreach (BPP item in tmp)
{
Blueprint.Add(item);
}
}
Console.ReadLine();
}
}
public class Order
{
public string Id { get; set; }
public string Name { get; set; }
}
public class BPP
{
public string Idzzz { get; set; }
public string BikeName { get; set; }
}
Sidenote: i am comparing the ID's in each of the lists! Hope it helps.
Hi so im trying to create an inventory system
but very strangely when i try and add 1 to the item amount of an item. it adds 3
so if i add 1 item the next time i add one it will appear as 4 then 10 then 22 then 46 ect ect ect instead of just going 1,2,3,4
ive followed the variables im entering and at all stages they return the correct 1
its only after ive added it to the item amount it suddenly become the 4,10 ect`
if (Input.GetKeyUp(KeyCode.Space))
{
Item test = new Item();
test.ItemName = "testsss";
test.ItemID = 55;
test.Stackable = true;
test.ItemAmount = 1;
AddItem(test);
}
public void AddItem(Item item)
{
if (!isLocalPlayer) return;
if (InventoryCurrentWeight + item.ItemWeight < InventoryMaxWeight)
{
if (item.Stackable == true)
{
checkIfItemExists(item);
InvGui();
}
else
{
addItemAtEmptySlot(item);
InvGui();
}
}
else
{
Debug.Log("Too Much Weight");
}
}
public void checkIfItemExists(Item item)
{
if (!isLocalPlayer) return;
for (int i = 0; i < inventory.Count; i++)
{
if (inventory[i].ItemID == item.ItemID)
{
Debug.Log(item.ItemAmount);
Debug.Log("Before" +inventory[i].ItemAmount);
inventory[i].ItemAmount = inventory[i].ItemAmount + item.ItemAmount;
//CaclutateWeight();
Debug.Log("After" + inventory[i].ItemAmount);
break;
}
else if (i == inventory.Count - 1)
{
addItemAtEmptySlot(item);
}
}
}
and this is my item class that holds the data `
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class Item
{
public string ItemName;
public string ItemDescription;
public float ItemWeight;
public int ItemID;
public int ItemAmount;
public ItemType itemType;
public string Sprite;
public bool Stackable;
public enum ItemType
{
Coin,
Weapon,
Armour,
craftingMat,
StatItem
}
public Item(string name,string desc, float weight, int id, int amount, ItemType type,bool stackable)
{
ItemName = name;
ItemDescription = desc;
ItemWeight = weight;
ItemID = id;
ItemAmount = amount;
itemType = type;
Stackable = stackable;
}
public Item()
{
}
}`
`
I have a text file call groceries. That contain text similar to the following:
regular,cereal,4.00,1;
fresh,rump steak,11.99,0.8;
The code below is trying to read the text file, split the string and then write to a text file called invoice.
The invoice text file should read read line in the groceries file, list whether it is a "fresh" or "regular" grocery item. If fresh GST is not applied if regular GST is applied. Calculate the cost on weight for fresh and quantity for regular and then display a total cost of items listed.
Any help would be appreciated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Groceries3
{
class Program
{
static void Main(string[] args)
{
string[] groceries = File.ReadAllLines ("Groceries.txt");
File.WriteAllLines("Invoice.txt", invoices.ToArray());
List<string> invoices = new List<string>();
FreshGrocery freshGrocery = new FreshGrocery();
freshGrocery.Name = "fresh";
freshGrocery.Price = 30;
freshGrocery.Weight = 0.5;
Grocery grocery = new Grocery();
grocery.Name = "regular";
grocery.Price = 50;
grocery.Quantity = 2;
double price = price.Calculate();
int counter = 0;
foreach (var grocery2 in groceries)
{
counter++;
invoices.Add(counter + "," + grocery + price+Quantity+"," + DateTime.Now.Date);
}
abstract class GroceryItem
{
private string name;
private double price = 0;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public double Price
{
get
{
return price;
}
set
{
price = value;
}
}
public abstract double Calculate();
}
class FreshGrocery : GroceryItem
{
private double weight = 0;
public double Weight
{
get
{
return weight;
}
set
{
weight = value;
}
}
public override double Calculate()
{
return this.Price * this.weight;
}
}
class Grocery : GroceryItem
{
private int quantity = 0;
private double gst = 10;
public int Quantity
{
get
{
return quantity;
}
set
{
quantity = value;
}
}
public override double Calculate()
{
double calculatedPrice = this.Price * this.Quantity;
if (calculatedPrice < 0)
{
calculatedPrice += calculatedPrice * (gst / 100);
}
return calculatedPrice;
}
}
class ShoppingCart
{
private List<GroceryItem> orders;
public List<GroceryItem> Orders
{
get
{
return orders;
}
set
{
orders = value;
}
}
public double Calculate()
{
double price = 0;
if (this.Orders != null)
{
foreach (GroceryItem order in this.Orders)
{
price += order.Calculate();
}
}
return price;
}
}
}
try something like that
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Groceries3
{
class Program
{
static void Main(string[] args)
{
string[] groceries = File.ReadAllLines("Groceries.txt");
List<string> invoices = new List<string>();
int counter = 0;
foreach (var grocery2 in groceries)
{
counter++;
var list = grocery2.Split(',');
if (list[0].Equals("fresh"))
{
FreshGrocery freshGrocery = new FreshGrocery();
freshGrocery.Name = list[1];
freshGrocery.Price = double.Parse(list[2]);
freshGrocery.Weight = double.Parse(list[3].Replace(";", ""));
invoices.Add(counter + "," + freshGrocery.Name + "," + freshGrocery.Price + "," + freshGrocery.Weight + "," + DateTime.Now.Date);
}
else if (list[0].Equals("regular"))
{
Grocery grocery = new Grocery();
grocery.Name = list[1];
grocery.Price = double.Parse(list[2]);
grocery.Quantity = int.Parse(list[3].Replace(";", ""));
double price = grocery.Calculate();
invoices.Add(counter + "," + grocery.Name + "," + price + "," + grocery.Quantity + "," + DateTime.Now.Date);
}
}
File.WriteAllLines("Invoice.txt", invoices.ToArray());
}
abstract class GroceryItem
{
private string name;
private double price = 0;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public double Price
{
get
{
return price;
}
set
{
price = value;
}
}
public abstract double Calculate();
}
class FreshGrocery : GroceryItem
{
private double weight = 0;
public double Weight
{
get
{
return weight;
}
set
{
weight = value;
}
}
public override double Calculate()
{
return this.Price * this.weight;
}
}
class Grocery : GroceryItem
{
private int quantity = 0;
private double gst = 10;
public int Quantity
{
get
{
return quantity;
}
set
{
quantity = value;
}
}
public override double Calculate()
{
double calculatedPrice = this.Price * this.Quantity;
if (calculatedPrice < 0)
{
calculatedPrice += calculatedPrice * (gst / 100);
}
return calculatedPrice;
}
}
class ShoppingCart
{
private List<GroceryItem> orders;
public List<GroceryItem> Orders
{
get
{
return orders;
}
set
{
orders = value;
}
}
public double Calculate()
{
double price = 0;
if (this.Orders != null)
{
foreach (GroceryItem order in this.Orders)
{
price += order.Calculate();
}
}
return price;
}
}
}
}
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);
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!");
}
}
}