does not contain a constructor - c#

Type definitions
using System;
public enum Direction { Right, Left, Forward };
class Chaharpa
{
private int age;
private int height;
private int cordinates_x;
private int cordinates_y;
public Chaharpa(int a, int b, int x, int y)
{
age = a;
height = b;
cordinates_x = x;
cordinates_y = y;
}
public Chaharpa(int c, int d)
{
age = c;
height = d;
cordinates_x = 0;
cordinates_y = 0;
}
public int Age
{
get { return age; }
}
public int Height
{
get { return height; }
}
public int Cordinates_x
{
get { return cordinates_x; }
set { cordinates_x = value; }
}
public int Cordinates_y
{
get { return cordinates_y; }
set { if (value > 0) cordinates_y = value; }
}
public void Move(Direction direction)
{
if (direction == Direction.Forward)
Cordinates_y++;
else if (direction == Direction.Right)
Cordinates_x++;
else if (direction == Direction.Left)
Cordinates_x--;
}
class horse : Chaharpa
{
public bool is_wild;
public void Jump(int x)
{
x = Cordinates_y;
Cordinates_y += 5;
}
public void Print()
{
Console.WriteLine("Horse Information: Age," + Age + ", Height: " + Height + ", Wild: " + is_wild + ", X: " + Cordinates_x + ", Y: " + Cordinates_y);
}
}
}
Usage
class Program
{
static void Main(string[] args)
{
int age, x, y, minAge = 0;
int height;
bool wild;
for (int i = 0; i < 3; i++)
{
Console.WriteLine("Horse #" + (i + 1));
Console.Write("Enter Age: ");
age = int.Parse(Console.ReadLine());
Console.Write("Enter Height: ");
height = int.Parse(Console.ReadLine());
Console.Write("Enter X: ");
x = int.Parse(Console.ReadLine());
Console.Write("Enter Y: ");
y = int.Parse(Console.ReadLine());
Console.Write("Is Wild: ");
wild = bool.Parse(Console.ReadLine());
minAge = age;
if (minAge > age)
{
minAge = age;
}
}
Console.WriteLine();
horse ob = new horse();
ob.Jump(minAge);
ob.move();
ob.Print();
Console.ReadKey();
}
}
I get these errors in Visual Studio:
'Chaharpa' does not contain a constructor that takes 0 arguments
The type or namespace name 'horse' could not be found (are you missing a using directive or an assembly reference?)
The type or namespace name 'horse' could not be found (are you missing a using directive or an assembly reference?)

In the class Chaharpa you defined two constructors, both take arguments.
Creating your own constructor overrides the default constructor.
Usually, when inheriting from a base class you want to initialize the inheriting class with parameters that are used to initialize the base class, look more at this thread.
The horse class inside Chaharpa and Chaharpaclass are not public.
Changing classes horse and Chaharpa to public and accessing it as:
Chaharpa.horse ob = new Chaharpa.horse();
is the right way to go.
Here are some mitigations to the code:
using System;
using System.ComponentModel;
public enum Direction
{ Right, Left, Forward };
public class Chaharpa
{
private int age;
private int height;
private int cordinates_x;
private int cordinates_y;
public Chaharpa()
{
}
public Chaharpa(int a, int b, int x, int y)
{
age = a;
height = b;
cordinates_x = x;
cordinates_y = y;
}
public Chaharpa(int c, int d)
{
age = c;
height = d;
cordinates_x = 0;
cordinates_y = 0;
}
public int Age
{
get { return age; }
}
public int Height
{
get { return height; }
}
public int Cordinates_x
{
get { return cordinates_x; }
set { cordinates_x = value; }
}
public int Cordinates_y
{
get { return cordinates_y; }
set { if (value > 0) cordinates_y = value; }
}
public void Move(Direction direction)
{
if (direction == Direction.Forward)
Cordinates_y++;
else if (direction == Direction.Right)
Cordinates_x++;
else if (direction == Direction.Left)
Cordinates_x--;
}
public class horse : Chaharpa
{
public bool is_wild;
public void Jump(int x)
{
x = Cordinates_y;
Cordinates_y += 5;
}
public void move()
{
throw new NotImplementedException();
}
public void Print()
{
Console.WriteLine("Horse Information: Age," + Age + ", Height: " + Height + ", Wild: " + is_wild + ", X: " + Cordinates_x + ", Y: " + Cordinates_y);
}
}
}
class Program
{
static void Main(string[] args)
{
int age, x, y, minAge = 0;
int height;
bool wild;
for (int i = 0; i < 3; i++)
{
Console.WriteLine("Horse #" + (i + 1));
Console.Write("Enter Age: ");
age = int.Parse(Console.ReadLine());
Console.Write("Enter Height: ");
height = int.Parse(Console.ReadLine());
Console.Write("Enter X: ");
x = int.Parse(Console.ReadLine());
Console.Write("Enter Y: ");
y = int.Parse(Console.ReadLine());
Console.Write("Is Wild: ");
wild = bool.Parse(Console.ReadLine());
minAge = age;
if (minAge > age)
{
minAge = age;
}
}
Console.WriteLine();
Chaharpa.horse ob = new Chaharpa.horse();
ob.Jump(minAge);
// You can call the Move defined in Chaharpa
ob.Move(<PASS DIRECTION PARAMETER HERE>);
ob.Print();
Console.ReadKey();
}
}

First, you have to study more about object creation in C#. When creating an object of a child class inside the child class constructor, it's calling the base class constructor.
using System;
public class Program
{
public static void Main()
{
Child child = new Child();
}
}
public class Parent{
public Parent(){
Console.WriteLine("I am parent");
}
}
public class Child : Parent {
public Child(){
Console.WriteLine("I am child");
}
}
Output
I am parent
I am child
When you creating a class there is a default constructor (the constructor which takes 0 arguments). But when you create another constructor (which takes more than 0 arguments) default constructor will replaced by that. You have to manually create default constructor. So at the runtime, it's trying to call the default constructor of the base class constructor. But since it's gone this error occurs.
'Chaharpa' does not contain a constructor that takes 0 arguments
Then you have to study about nested classes in C#.
You can't just call inner class by it's name. You have to reference it from the outer class.
using System;
public class Program
{
public static void Main()
{
Outer.Inner child = new Outer.Inner();
}
}
public class Outer{
public Outer(){
Console.WriteLine("I am outer");
}
public class Inner : Outer {
public Inner(){
Console.WriteLine("I am inner");
}
}
}
Output
I am outer
I am inner
That's why you get the error The type or namespace name 'horse' could not be found (are you missing a using directive or an assembly reference?)
This code will work.
using System;
public enum Direction
{ Right, Left,Forward};
class Chaharpa
{
private int age;
private int height;
private int cordinates_x;
private int cordinates_y;
public Chaharpa(){}
public Chaharpa(int a, int b, int x, int y)
{
age = a;
height = b;
cordinates_x = x;
cordinates_y = y;
}
public Chaharpa(int c, int d)
{
age = c;
height = d;
cordinates_x = 0;
cordinates_y = 0;
}
public int Age
{
get{ return age; }
}
public int Height
{
get{ return height;}
}
public int Cordinates_x
{
get{ return cordinates_x;}
set{ cordinates_x = value;}
}
public int Cordinates_y
{
get{return cordinates_y;}
set{ if (value > 0)cordinates_y = value;}
}
public void Move(Direction direction)
{
if (direction == Direction.Forward)
Cordinates_y++;
else if (direction == Direction.Right)
Cordinates_x++;
else if (direction == Direction.Left)
Cordinates_x--;
}
public class horse : Chaharpa
{
public bool is_wild;
public void Jump(int x)
{
x = Cordinates_y;
Cordinates_y += 5;
}
public void Print()
{
Console.WriteLine("Horse Information: Age," + Age + ", Height: " + Height + ", Wild: " + is_wild + ", X: " + Cordinates_x + ", Y: " + Cordinates_y);
}
}
}
public class Program
{
public static void Main(string[] args)
{
int age, x, y, minAge = 0;
int height;
bool wild;
for (int i = 0; i < 3; i++)
{
Console.WriteLine("Horse #" + (i + 1));
Console.Write("Enter Age: ");
age = int.Parse(Console.ReadLine());
Console.Write("Enter Height: ");
height = int.Parse(Console.ReadLine());
Console.Write("Enter X: ");
x = int.Parse(Console.ReadLine());
Console.Write("Enter Y: ");
y = int.Parse(Console.ReadLine());
Console.Write("Is Wild: ");
wild = bool.Parse(Console.ReadLine());
minAge = age;
if (minAge > age)
{
minAge = age;
}
}
Console.WriteLine();
Chaharpa.horse ob = new Chaharpa.horse();
ob.Jump(minAge);
ob.Print();
}
}
Use one file for one class is a good practice.

Related

Reading a txt file, split string then write to txt file

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

Delete function for simple inventory

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.

Error: class does not contain a definition and no extension method

In my code below, it is supposed to do the following tasks:
Prompt the user for values for each Order. Do not allow duplicate order numbers; force the user to reenter the order when a duplicate order number is entered. When five valid orders have been entered, display them all, plus a total of all orders.
The problem is that there are errors in it. I tried to solve the errors by myself but I can't fix it. I've been stuck in these errors for many hours. And another thing, I can't really understand why does it displays that OrderDemo does not contain a definition for Total, OrderNumber, Customer and Quantity. Any help given would be very much appreciated. Thanks!
using System;
class OrderDemo
{
public static void Main()
{
OrderDemo[] order = new OrderDemo[5];
int x, y;
double grandTotal = 0;
bool goodNum;
for (x = 0; x < order.Length; ++x)
{
order[x] = new Order(); //OrderDemo.Order does not contain a constructor that takes 0 arguments
Console.Write("Enter order number");
order[x].OrderNumber = Convert.ToInt32(Console.ReadLine());
goodNum = true;
for (y = 0; y < x; ++y)
{
if (order[x].Equals(order[y]))
goodNum = false;
}
while (!goodNum)
{
Console.Write("sorry, the order number " + order[x].OrderNumber + "is a duplicate. " + "\nPlease reenter: ");
order[x].OrderNumber = Convert.ToInt32(Console.ReadLine());//OrderDemo does not contain a definition for OrderNumber and no extension..
goodNum = true;
for (y = 0; y > x; ++y)
{
if (order[x].Equals(order[y]))
goodNum = false;
}
}
Console.Write("Enter customer name");
order[x].Customer = Console.ReadLine();//OrderDemo does not contain a definition for Customer and no extension..
Console.Write("Enter Quantity");
order[x].Quantity = Convert.ToInt32(Console.ReadLine());//OrderDemo does not contain a definition for Quantity and no extension..
}
Console.WriteLine("\nSummary\n");
for (x = 0; x < order.Length; ++x)
{
Console.WriteLine(order[x].ToString());
grandTotal += order[x].Total; //OrderDemo does not contain a definition for Total and no extension..
}
Console.WriteLine(" Total for all orders is" + grandTotal.ToString("c"));
}
public class Order
{
public int orderNum;
public string cusName;
public int quantity;
public double total;
public const double ItemPrice = 19.95;
public Order(int ordNum, string cusName, int numOrdered)
{
OrderNum = ordNum;
Customer = cusName;
Quantity = numOrdered;
}
public int OrderNum
{
get { return orderNum; }
set { orderNum = value; }
}
public string Customer
{
get { return cusName; }
set { cusName = value; }
}
public int Quantity
{
get
{
return quantity;
}
set
{
quantity = value;
total = quantity * ItemPrice;
}
}
public double Total
{
get
{
return total;
}
}
public override string ToString()
{
return ("Order " + OrderNum + " " + Customer + " " + Quantity +
" #Php" + ItemPrice.ToString("0.00") + " each. " + "The total is Php" + Total.ToString("0.00"));
}
public override bool Equals(Object e)
{
bool equal;
Order temp = (Order)e;
if (OrderNum == temp.OrderNum)
equal = true;
else
equal = false;
return equal;
}
public override int GetHashCode()
{
return OrderNum;
}
}
}
You declared your array as containing OrderDemo objects.
As the error clearly states, OrderDemo doesn't have any properties.
You probably mean Order, which is a different class.
C# provides a default constructor for you, as long as you don't define other constructors which accept parameters. Because you have this:
public Order(int ordNum, string cusName, int numOrdered)
{
OrderNum = ordNum;
Customer = cusName;
Quantity = numOrdered;
}
The default constructor isn't generated. You need to add this:
public Order() { }
...if you want to create objects without passing parameters to it.
Also, as SLaks has pointed out, you have declared your array incorrectly:
OrderDemo[] order = new OrderDemo[5];
Should be this instead:
var order = new Order[5]; // or Order[] order = new Order[5];

Sorting array in ascending order error

My code below works fine but what I want to do is to display the summary in ascending order according to its OrderNum. I tried to put Array.Sort(order[x].OrderNum) but error cannot convert from int to System.Array. Any suggestions on how I can sort this? Thank you very much!
using System;
class ShippedOrder
{
public static void Main()
{
Order[] order = new Order[5];
int x, y;
double grandTotal = 0;
bool goodNum;
for (x = 0; x < order.Length; ++x)
{
order[x] = new Order();
Console.Write("Enter order number: ");
order[x].OrderNum = Convert.ToInt32(Console.ReadLine());
goodNum = true;
for (y = 0; y < x; ++y)
{
if (order[x].Equals(order[y]))
goodNum = false;
}
while (!goodNum)
{
Console.Write("Sorry, the order number " + order[x].OrderNum + " is a duplicate. " + "\nPlease re-enter: ");
order[x].OrderNum = Convert.ToInt32(Console.ReadLine());
goodNum = true;
for (y = 0; y > x; ++y)
{
if (order[x].Equals(order[y]))
goodNum = false;
}
}
Console.Write("Enter customer name: ");
order[x].Customer = Console.ReadLine();
Console.Write("Enter Quantity: ");
order[x].Quantity = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("\nSummary:\n");
for (x = 0; x < order.Length; ++x)
{
Array.Sort(order[x].OrderNum); //This line is where the error is located
Console.WriteLine(order[x].ToString());
grandTotal += order[x].Total;
}
Console.WriteLine("\nTotal for all orders is Php" + grandTotal.ToString("0.00"));
Console.Read();
}
public class Order
{
public int orderNum;
public string cusName;
public int quantity;
public double total;
public const double ItemPrice = 19.95;
public Order() { }
public Order(int ordNum, string cusName, int numOrdered)
{
OrderNum = ordNum;
Customer = cusName;
Quantity = numOrdered;
}
public int OrderNum
{
get { return orderNum; }
set { orderNum = value; }
}
public string Customer
{
get { return cusName; }
set { cusName = value; }
}
public int Quantity
{
get
{
return quantity;
}
set
{
quantity = value;
total = quantity * ItemPrice + 4;
}
}
public double Total
{
get
{
return total;
}
}
public override string ToString()
{
return ("ShippedOrder " + OrderNum + " " + Customer + " " + Quantity +
" #Php" + ItemPrice.ToString("0.00") + " each. " + "Shipping is Php4.00\n" + " The total is Php" + Total.ToString("0.00"));
}
public override bool Equals(Object e)
{
bool equal;
Order temp = (Order)e;
if (OrderNum == temp.OrderNum)
equal = true;
else
equal = false;
return equal;
}
public override int GetHashCode()
{
return OrderNum;
}
}
}
Just use Linq:
order = order.OrderBy(x => x.OrderNum).ToArray();
While looking this link, found that Array.Sort will not take integer as parameter.
You have to pass all the data as Array object.
Try the following:
order.Sort( delegate (Order o1, Order o2) {
return o1.OrderNum.CompareTo(o2.OrderNum);
});

C# adding values to an instance after using a constructor

Can I add values to an instance of an object after I have used the constructor?
For instance I have this code. I have to make a list of objects which require a number n, and the time (which are recieved as arguments). The problem is that the time can be anywhere so I can't use it in a constructor.
public List<IAction> Dispatch(string[] arg)
{
int time;
int i = 0;
int j = 0;
List<IAction> t = new List<IAction>(10);
do
{
if (int.Parse(arg[j]) >= 0 && int.Parse(arg[j]) <= 20)
{
t.Add(new ComputeParam(int.Parse(arg[j])));
i++;
j++;
}
else
{
if (arg[i][0] == '/' && arg[i][1] == 't')
{
Options opt = new Options();
j++;
time=opt.Option(arg[i]); //sets the time 0,1000 or 2000
}
}
} while (i != arg.Length);
return t;
}
After finishing making the list can I do something like:
for(int i=0; i<=t.Count; i++)
{
*add time to t[i]*
}
How do I do this?
Thanks in advance!
Edit :
here is the ComputeParam class
public class ComputeParam : IAction
{
int n;
int time;
public ComputeParam()
{
}
public ComputeParam(int n)
{
this.n = n;
}
public void run()
{
Factorial Fact = new Factorial();
Fact.Progression += new Factorial.ProgressEventHandler(Progress);
Console.WriteLine(" ");
Console.Write("\n" + "Partial results : ");
Console.CursorLeft = 35;
Console.Write("Progress : ");
int Result = Fact.CalculateFactorial(n, time);
Console.WriteLine(" ");
Console.WriteLine("The factorial of " + n + " is : " + Result);
Console.WriteLine("Press Enter to continue...");
Console.CursorTop -= 2;
Console.CursorLeft = 0;
Console.ReadLine();
}
public void Progress(ProgressEventArgs e)
{
int result = e.getPartialResult;
int stack_value = e.getValue;
double max = System.Convert.ToDouble(n);
System.Convert.ToDouble(stack_value);
double percent = (stack_value / max) * 100;
Console.CursorLeft = 18;
Console.Write(result + " ");
Console.CursorLeft = 46;
Console.Write(System.Convert.ToInt32(percent) + "% ");
}
}
If the object has a public property, I don't see why not.
Edit: Looks like you need to add a public property to your class. Also note, given that there is a public constructor that takes 0 params, you should also add a property for n.
public class ComputeParam : IAction
{
int _n;
int _time;
public ComputeParam()
{
}
public ComputeParam(int n)
{
this._n = n;
}
public int Time
{
get { return this._time; }
set { this._time = value; }
}
public int N
{
get { return this._n; }
set { this._n = value; }
}
for(int i = 0; i < t.Count; i++)
{
((ComputeParam)t[i]).Time = 6;
}

Categories