I have been searching about creating a new object within a loop, found some answers and topics but its way too hard to understand. Making it with lists and arrays etc.
What I am trying to do is, get an input from the user(lets say 3), and create objects as many as the user will with the unique names. Like newperson1, newperson2, newperson3 etc.
My code looks like this:
class person
{
}
class Program
{
static void Main(string[] args)
{
Console.Write("How many persons you want to add?: ");
int p = int.Parse(Console.ReadLine());
for (int i = 0; i < p; i++)
{
person newperson = new person();
}
}
}
Is there any way to create new objects with following numbers in the end of the object name?
Thanks!
Edit:
My new code looks like this; I was more thinking like this:
class Persons
{
//Person object id
public int id { get; set; }
//Persons name
public string name { get; set; }
//Persons adress
public string adress { get; set; }
//Persons age
public int age { get; set; }
}
class Program
{
static void Main(string[] args)
{
Console.Write("How many persons you want to add?: ");
int count = int.Parse(Console.ReadLine());
var newPersons = new List<Persons>(count);
for (int i = 0; i < count; i++)
{
newPersons[i].id = i;
Console.Write("Write name for person " + i);
newPersons[i].name = Console.ReadLine();
Console.Write("Write age for person " + i);
newPersons[i].age = int.Parse(Console.ReadLine());
Console.Write("Write adress for person " + i );
newPersons[i].adress = Console.ReadLine();
}
Console.WriteLine("\nPersons \tName \tAge \tAdress");
for (int i = 0; i < count; i++)
{
Console.WriteLine("\t" + newPersons[i].name + "\t" + newPersons[i].age + "\t" + newPersons[i].adress);
}
Console.ReadKey();
}
}
I understand that I have to create object with arrays or lists. But I didn't really understand how I will access them after they are created person by person..
It's fairly advanced to create dynamic classes (where the actual name of the object is different). In other words, it's WAY harder to do what you're asking than to create a List or an Array. If you spend an hour or two studying Collections, it will pay off in the long run.
Also, you might consider adding a Name property to your Person class, and then you can set that differently for each person you create.
As others have said, you will need to store them in an array or list:
public class Person
{
public string Name { get; set; }
}
static void Main(string[] args)
{
Console.Write("How many persons you want to add?: ");
int p = int.Parse(Console.ReadLine());
var people = new List<Person>();
for (int i = 0; i < p; i++)
{
// Here you can give each person a custom name based on a number
people.Add(new Person { Name = "Person #" + (i + 1) });
}
}
Here's an example of one way to access a Person from the list and let the user update the information. Note that I've added a few properties to the Person class:
public class Person
{
public string Name { get; set; }
public DateTime DateOfBirth { get; set; }
public string Address { get; set; }
public int Age
{
// Calculate the person's age based on the current date and their birthday
get
{
int years = DateTime.Today.Year - DateOfBirth.Year;
// If they haven't had the birthday yet, subtract one
if (DateTime.Today.Month < DateOfBirth.Month ||
(DateTime.Today.Month == DateOfBirth.Month &&
DateTime.Today.Day < DateOfBirth.Day))
{
years--;
}
return years;
}
}
}
private static void GenericTester()
{
Console.Write("How many persons you want to add?: ");
string input = Console.ReadLine();
int numPeople = 0;
// Make sure the user enters an integer by using TryParse
while (!int.TryParse(input, out numPeople))
{
Console.Write("Invalid number. How many people do you want to add: ");
input = Console.ReadLine();
}
var people = new List<Person>();
for (int i = 0; i < numPeople; i++)
{
// Here you can give each person a custom name based on a number
people.Add(new Person { Name = "Person" + (i + 1) });
}
Console.WriteLine("Great! We've created {0} people. Their temporary names are:",
numPeople);
people.ForEach(person => Console.WriteLine(person.Name));
Console.WriteLine("Enter the name of the person you want to edit: ");
input = Console.ReadLine();
// Get the name of a person to edit from the user
while (!people.Any(person => person.Name.Equals(input,
StringComparison.OrdinalIgnoreCase)))
{
Console.Write("Sorry, that person doesn't exist. Please try again: ");
input = Console.ReadLine();
}
// Grab a reference to the person the user asked for
Person selectedPerson = people.First(person => person.Name.Equals(input,
StringComparison.OrdinalIgnoreCase));
// Ask for updated information:
Console.Write("Enter a new name (or press enter to keep the default): ");
input = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(input))
{
selectedPerson.Name = input;
}
Console.Write("Enter {0}'s birthday (or press enter to keep the default) " +
"(mm//dd//yy): ", selectedPerson.Name);
input = Console.ReadLine();
DateTime newBirthday = selectedPerson.DateOfBirth;
if (!string.IsNullOrWhiteSpace(input))
{
// Make sure they enter a valid date
while (!DateTime.TryParse(input, out newBirthday) &&
DateTime.Today.Subtract(newBirthday).TotalDays >= 0)
{
Console.Write("You must enter a valid, non-future date. Try again: ");
input = Console.ReadLine();
}
}
selectedPerson.DateOfBirth = newBirthday;
Console.Write("Enter {0}'s address (or press enter to keep the default): ",
selectedPerson.Name);
input = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(input))
{
selectedPerson.Address = input;
}
Console.WriteLine("Thank you! Here is the updated information:");
Console.WriteLine(" - Name ............ {0}", selectedPerson.Name);
Console.WriteLine(" - Address ......... {0}", selectedPerson.Address);
Console.WriteLine(" - Date of Birth ... {0}", selectedPerson.DateOfBirth);
Console.WriteLine(" - Age ............. {0}", selectedPerson.Age);
}
The closest thing to doing what you are asking is to create a dictionary:
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var dictionary = new Dictionary<string, Person>();
Console.Write("How many persons you want to add?: ");
int p = int.Parse(Console.ReadLine());
for (int i = 0; i < p; i++)
{
dictionary.Add("NewPerson" + i, new Person());
}
// You can access them like this:
dictionary["NewPerson1"].Name = "Tim Jones";
dictionary["NewPerson2"].Name = "Joe Smith";
}
public class Person
{
public string Name {
get;
set;
}
}
}
You can create dynamically named variables in C#.
What you need is a collection of persons:
var persons = new List<person>();
for (int i = 0; i < p; i++)
{
persons.Add(new person());
}
Arrays and List are basic building blocks. they should't be very hard. but if you don't want to deal with them try creating a method whose responsibility is to give you your new objects given count.
static void Main(string[] args)
{
Console.Write("How many persons you want to add?: ");
int p = int.Parse(Console.ReadLine());
var newPersons = CreatePersons(p);
foreach (var person in newPersons)
{
Console.WriteLine("Eneter age for Person :" person.Name);
person.Age = Console.ReadLine();
}
}
static IEnumerable<Person> CreatePersons(int count)
{
for (int i = 0; i < count; i++)
{
yield return new Person{ Name="newPerson" +1 };
}
}
Try this one.
I am creating Person (Object) as array first (like creating object array)
Then I am assigning that to the Person Class.
class Persons
{
//Person object id
public int id { get; set; }
//Persons name
public string name { get; set; }
//Persons adress
public string adress { get; set; }
//Persons age
public int age { get; set; }
}
class Program
{
static void Main(string[] args)
{
Console.Write("How many persons you want to add?: ");
int count = int.Parse(Console.ReadLine());
//var newPersons = new List<Persons>(count);
Persons[] newPersons = new Persons[count];
for (int i = 0; i < count; i++)
{
newPersons[i] = new Persons();
newPersons[i].id = i+1;
Console.Write("Write name for person " + (i+1) + "\t");
newPersons[i].name = Console.ReadLine();
Console.Write("Write age for person " + (i + 1) + "\t");
newPersons[i].age = int.Parse(Console.ReadLine());
Console.Write("Write adress for person " + (i + 1) + "\t");
newPersons[i].adress = Console.ReadLine();
}
Console.WriteLine("\nPersons Name \tAge \tAdresss \n");
for (int i = 0; i < count; i++)
{
Console.WriteLine(newPersons[i].name + "\t\t" + newPersons[i].age + "\t" + newPersons[i].adress);
}
Console.ReadKey();
}
}
If you want to iterate through an array of object in C#, you need to define the ToString() method (override) and after that, you can use the ToString() method.
Related
namespace HW
{
class Program
{
struct Employee
{
int join_year;
int age;
string dept;
public void getval(int join_year, int age, string dept)
{
this.join_year = join_year;
this.age = age;
this.dept = dept;
}
public void showval()
{
Console.WriteLine("Joining year of Employee is: {0}", this.join_year);
Console.WriteLine("Age of Employee is: {0}", this.age);
Console.WriteLine("Department of Employee is: {0}", this.dept);
}
}
static void Main(string[] args)
{
Employee emp = new Employee();
Console.Write("Enter Joining Year: ");
int join_year = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter Age: ");
int age = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter Department: ");
string dept = Console.ReadLine();
emp.getval(join_year, age, dept);
emp.showval();
}
}
}
So yeah basically over here I'm adding the values and they are getting printed too. Now I just want to take these records add it into a list or array so that I can access the records by choice.
if I understand it right, you want to do this.
List<string>() list = new List<string>();
for(int i = 0; i < 3; i++)
{
switch(i)
{
case 0: list.Add(join_year.ToString());
break;
case 1: list.Add(age.ToString());
break;
case 2: list.Add(dept);
break;
}
}
it is pretty simplistic, but will do the job.
so far my code does the following.
Ask user for a numeric amount for 'players'
Then asks for names for each of the players which is added to a list and class
I'd like to call those names from the list or class (not really sure how class works) and assign it to a new string. Here's what I got so far:
public class NameVariable
{
public int ID { get; set; }
public string Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
bool IsUserWrong = false;
Console.WriteLine("Write amount of players");
while (!IsUserWrong)
{
int TotalPlayers;
while (!Int32.TryParse(Console.ReadLine(), out TotalPlayers))
{
Console.WriteLine("Value must be numeric.");
}
if (TotalPlayers >= 12 && TotalPlayers <= 16)
{
List<NameVariable> PlayerList = new List<NameVariable>();
for (int index = 0; index < TotalPlayers; index++)
{
Console.WriteLine("Enter player {0}'s name:", index + 1);
PlayerList.Add(new NameVariable
{
Name = Console.ReadLine(),
ID = index
});
}
// string player1 = ???
// string player2 = ???
// and so on for 12-16 players
}
else
{
Console.WriteLine("Please enter a value between 12 and 16.");
}
}
}
}
I know that a foreach loop can be used to display all of the variables in the NameVariable class. Would just like to know how to assign each variable to a different string.
Before using the class I just used the list which worked by using
string player1 = PlayerList[0];
string player2 = PlayerList[1];
// and so on for the remaining players
Thanks in advance!
it's just
string player1 = PlayerList[0].Name;
string player2 = PlayerList[1].Name;
...
Essentially your list contains NameVariable objects. PlayerList[index] gives you the object, and .Name gives you the property value of the object.
If you want a specific player name by a specific ID number, you can use LINQ (just to give you a hint)
string player = PlayerList.Where(p => p.ID == WhateverIDNumber).First().Name;
While the answer to your immediate question, i.e., how to access properties of a class object, is as others have shown, I feel like this code has a bigger problem. That is you're trying to do too much in one function, namely, Main(). So I advice to in fact try and refactor your code so that one function does one thing. Something like:
public static int GetNumberOfPlayers()
{
Console.Write("Enter number of players: ");
int totalPlayers;
while (!Int32.TryParse(Console.ReadLine(), out totalPlayers))
{
Console.WriteLine("Value must be numeric.");
}
return totalPlayers;
}
public static List<NameVariable> GetPlayerList(int num)
{
var list = new List<NameVariable>();
for (int i = 0; i < num; i++)
{
Console.WriteLine("Enter player {0}'s name:", i + 1);
list.Add(new NameVariable
{
Name = Console.ReadLine(),
ID = i
});
}
return list;
}
public static void DisplayPlayers(List<NameVariable> list)
{
foreach(var player in list)
{
Console.WriteLine("Player {0}, Name: {1}", player.ID, player.Name);
}
}
public static void CantThinkOfAGoodName()
{
while (true)
{
int totalPlayers = GetNumberOfPlayers();
if (totalPlayers > 16 || totalPlayers < 12)
{
Console.WriteLine("Please enter a value between 12 and 16.");
}
else
{
var playerList = GetPlayerList(totalPlayers);
DisplayPlayers(playerList);
break;
}
}
}
public static void Main()
{
CantThinkOfAGoodName();
Console.ReadLine();
}
Not sure if it helps but you can use an indexer to get players by name.
public NameVariable this[string name]
Let's say you create a class for the colection
public class NameColection : List<NameVariable>
{
public NameVariable this[string name]
{
get
{
return this.FirstOrDefault(n => n.Name == name);
}
}
}
Then you access players by name
var players = new NameColection()
{
new NameVariable() { ID = 1 , Name = "John" },
new NameVariable() { ID = 2 , Name = "Paul" },
new NameVariable() { ID = 3 , Name = "George" },
new NameVariable() { ID = 4 , Name = "Ringo" }
};
var player1 = players["John"];
As NameColection inhertits from List, you will be able to add, remove or modify items the usual way.
class Program
{
struct St_test
{
public string f_name;
public string l_name;
public int age;
public string email;
}
static void proced(int number)
{
St_test s = new St_test();
Console.WriteLine("Enter the first name :");
s.f_name = Console.ReadLine();
Console.WriteLine("Enter the last name :");
s.l_name = Console.ReadLine();
agee:
Console.WriteLine("Enter the age :");
try { s.age = int.Parse(Console.ReadLine()); }
catch { Console.WriteLine("You enterd viod age"); goto agee; }
Console.WriteLine("Enter the e_mail :");
s.email = Console.ReadLine();
}
static void Main(string[] args)
{
int num;
nume:
Console.WriteLine("enter the count of people you would like to store");
try { num = int.Parse(Console.ReadLine()); }
catch { Console.WriteLine("you enterd void number"); goto nume; }
for (int i = 0; i < num; i++)
{
proced(num);
}
I want to input many of (S) to every number (num) of people.
How to repeat the procedure (proced) and every repeat the (s) variable has new name.
If I write in the procedure (proced) the next :
string r = "s" + number;
how to convert the resulted string (r) to variable to use it instead of (s) variable for each loop
You can't (easily, anyway) access variables by name like that - but there's a much better solution, which is to create a collection of some kind - an array or a list, for example.
I would suggest:
Changing your St_test struct:
Make it a non-nested type
Give it a clearer name (e.g. Person)
Make it a class
Don't expose fields - expose properties
Potentially make it immutable, taking all the values in the constructor
Changing your proced method:
Make it return a new Person
Change the name to follow .NET naming conventions
Stop using goto
Factor out the "request an integer from the user" into a method
Changing your Main method:
Create a List<Person>
Repeatedly call what used to be called proced. but add the return value into the list
You'll end up with code something like this - but don't blindly copy it. Make sure you understand everything that's happening here.
using System;
using System.Collections.Generic;
public sealed class Person
{
public string FirstName { get; }
public string LastName { get; }
public int Age { get; }
public string Email { get; }
public Person(string firstName, string lastName, int age, string email)
{
// TODO: Validation
FirstName = firstName;
LastName = lastName;
Age = age;
Email = email;
}
}
public class Test
{
private static Person CreatePersonFromUserInput()
{
Console.WriteLine("Enter the first name:");
string firstName = Console.ReadLine();
Console.WriteLine("Enter the last name:");
string lastName = Console.ReadLine();
Console.WriteLine("Enter the age:");
int age = RequestInt32();
Console.WriteLine("Enter the email address:");
string email = Console.ReadLine();
return new Person(firstName, lastName, age, email);
}
private static int RequestInt32()
{
string text = Console.ReadLine();
int ret;
while (!int.TryParse(text, out ret))
{
Console.WriteLine("Invalid value. Please try again.");
text = Console.ReadLine();
}
return ret;
}
private static void Main()
{
Console.WriteLine("Enter the count of people you would like to store:");
int count = RequestInt32();
List<Person> people = new List<Person>();
for (int i = 0; i < count; i++)
{
people.Add(CreatePersonFromUserInput());
}
// Just to show them...
foreach (Person person in people)
{
Console.WriteLine(
$"First: {person.FirstName}; Last: {person.LastName}; Age: {person.Age}; Email: {person.Email}");
}
}
}
I am creating a program that intakes info for the number of visits on separate days to a centre. I am using an array to keep track of that info, but I also need to create a method that calls up the day with the least number of visits and then displays it in an output.
class ScienceCentreVisitation
{
private string centreName;
private string city;
private decimal ticketPrice;
private string[] visitDate;
private int[] adultVisitors;
private decimal[] totalRevenue;
//constructors
public ScienceCentreVisitation()
{
}
public ScienceCentreVisitation(string cent)
{
centreName = cent;
}
public ScienceCentreVisitation(string cent, string cit, decimal price, string[] date, int[] visit, decimal[] rev)
{
visitDate = new string[date.Length];
adultVisitors = new int[visit.Length];
totalRevenue = new decimal[rev.Length];
Array.Copy(date, 0, visitDate, 0, date.Length);
Array.Copy(visit, 0, adultVisitors, 0, adultVisitors.Length);
Array.Copy(rev, 0, totalRevenue, 0, rev.Length);
centreName = cent;
city = cit;
ticketPrice = price;
}
//properties
public string CentreName
{
get
{
return centreName;
}
set
{
centreName = value;
}
}
public string City
{
get
{
return city;
}
set
{
city = value;
}
}
public decimal TicketPrice
{
get
{
return ticketPrice;
}
set
{
ticketPrice = value;
}
}
public string[] VisitDate
{
get
{
return visitDate;
}
set
{
visitDate = value;
}
}
public int[] AdultVisitors
{
get
{
return adultVisitors;
}
set
{
adultVisitors = value;
}
}
public decimal[] TotalRevenue
{
get
{
return totalRevenue;
}
set
{
totalRevenue = value;
}
}
//methods
public decimal CalculateTotalRevenue()
{
decimal totalRev;
int cntOfValidEntries;
int total = 0;
foreach (int c in adultVisitors)
total += c;
cntOfValidEntries = TestForZeros();
totalRev = (decimal)total / cntOfValidEntries;
return totalRev;
}
public int TestForZeros()
{
int numberOfTrueVisits = 0;
foreach (int cnt in adultVisitors)
if (cnt != 0)
numberOfTrueVisits++;
return numberOfTrueVisits;
}
public int GetIndexOfLeastVisited()
{
int minVisIndex = 0;
for (int i = 1; i < adultVisitors.Length; i++)
if (adultVisitors[i] < adultVisitors[minVisIndex])
minVisIndex = i;
return minVisIndex;
}
public int GetLeastVisited()
{
return adultVisitors[GetIndexOfLeastVisited()];
}
public string GetDateWithLeastVisited()
{
return visitDate[GetIndexOfLeastVisited()];
}
public int GetIndexOfMostRevenue()
{
int maxRevIndex = 0;
for (int i = 1; i < totalRevenue.Length; i++)
if (totalRevenue[i] > totalRevenue[maxRevIndex])
maxRevIndex = i;
return maxRevIndex;
}
public decimal GetMostRevenue()
{
return totalRevenue[GetIndexOfMostRevenue()];
}
public string GetDateWithMostRevenue()
{
return visitDate[GetIndexOfMostRevenue()];
}
public override string ToString()
{
return "Name of Centre: " + centreName +
"\nCity: " + city +
"\n Price of ticket: " + ticketPrice +
"\nDate of Least One-Day Adult Visitors:\t\t" + GetDateWithLeastVisited() +
"\nNumber of Least One-Day Adult Visitors:\t\t" + GetLeastVisited() +
"\nDate of Most Total Revenue Collected:\t\t" + GetDateWithMostRevenue() +
"\nHighest Total Revenue Collected:\t\t" + GetMostRevenue();
}
}
Other class:
class ScienceCentreApp
{
static void Main(string[] args)
{
string centreName;
string city;
decimal ticketPrice = 0;
int visitorCnt;
string[] dArray = new String[5];
int[] adultVisitors = new int[5];
decimal[] totalRevenue = new decimal[5];
char enterMoreData = 'Y';
ScienceCentreVisitation scv;
do
{
visitorCnt = GetData(out centreName, out city, out ticketPrice, dArray, adultVisitors, totalRevenue);
scv = new ScienceCentreVisitation(centreName, city, ticketPrice, dArray, adultVisitors, totalRevenue);
Console.Clear();
Console.WriteLine(scv);
Console.Write("\n\n\n\nDo you want to enter more data - " +
"(Enter y or n)? ");
if (char.TryParse(Console.ReadLine(), out enterMoreData) == false)
Console.WriteLine("Invalid data entered - " +
"No recorded for your respones");
} while (enterMoreData == 'y' || enterMoreData == 'y');
Console.ReadKey();
}
public static int GetData(out string centreName, out string city, out decimal ticketPrice, string[] dArray, int[] adultVisitors, decimal[] totalRevenue)
{
int i,
loopCnt;
Console.Clear();
Console.Write("Name of Centre: ");
centreName = Console.ReadLine();
Console.Write("City: ");
city = Console.ReadLine();
Console.Write("Ticket Price: ");
string inValue = Console.ReadLine();
ticketPrice = Convert.ToDecimal(inValue);
Console.Write("How many records for {0}? ", centreName);
string inValue1 = Console.ReadLine();
if (int.TryParse(inValue1, out loopCnt) == false)
Console.WriteLine("Invalid data entered - " +
"0 recorded for number of records");
for (i = 0; i < loopCnt; i++)
{
Console.Write("\nDate (mm/dd/yyyy): ");
dArray[i] = Console.ReadLine();
if (dArray[i] == "")
{
Console.WriteLine("No date entered - " +
"Unknown recorded for visits");
dArray[i] = "Unknown";
}
Console.Write("Number of One-Day Adult Visitors: ");
inValue1 = Console.ReadLine();
if (int.TryParse(inValue1, out adultVisitors[i]) == false)
Console.WriteLine("Invalid data entered - " +
"0 recorded for adults visited");
}
return i;
}
}
I had it working before I made some changes to my program, but now it keeps coming up blank when I run it. Any idea why?
Without having the complete code it's difficult to debug this for you.
But here's a suggestion that came up when I was reading the start of your question:
It seems like the basic gist would be to use a Dictionary<DateTime, int> which would store the number of visits for each day.
Then you can use a simple LINQ query to get the smallest value:
dictionary.OrderBy(kvp => kvp.Value).First()
Of course, you can use a complex class in place of the int and store more data (location, price of admission for that day, adult visits, etc.).
class CenterVisitations
{
internal int Visitations { get; set; }
internal decimal TicketPrice { get; set; }
internal string Location { get; set; }
//add other stuff here, possibly create another class
//to store TicketPrice, Location and other static center data
//and create a reference to that here, instead of the above
//TicketPrice and Location...
}
Then you can define your dictionary like so:
Dictionary<DateTime, CenterVisitations>
And query it almost the same was as last time:
dictionary.Order(kvp => kvp.Value.Visitations).First();
Sorting and selecting would work the same way. Additionally you could add a .Where query to set a range of dates which you want to check:
dictionary.Where(kvp => kvp.Key < DateTime.Today && kvp.Key > DateTime.Today.AddDays(-7)) will only look for the last weeks worth of data.
It also seems you're keeping your data in separate arrays, which means querying it is that much harder. Finally, consider converting dates into DateTime objects rather than strings.
I'm working on a homework assignment, everything works except the binary search. When the program executes, I get the following error in Friend temp = (Friend)o; of the IComparable: InvalidCastException was unhandled by user code. Unable to cast object of type 'System.String' to type 'FriendList.Friend'. I could use help to pinpoint where I'm misguided. Thanks in advance.
using System;
using System.Linq;
namespace FriendList
{
public static class FriendList
{
public static void Main()
{
var findname = "";
var friends = new Friend[8];
for (var i = 0; i < 8; i++)
{
Console.Write("Enter a name (or type quit to skip): ");
var name = Console.ReadLine();
if (name.ToLower() == "quit")
{
return;
}
Console.Write("Enter a phone number: ");
var phone = Console.ReadLine();
Console.Write("Enter a birth month number: ");
var month = Console.ReadLine();
Console.Write("Enter a birth day: ");
var day = Console.ReadLine();
Console.Write("Enter a birth year: ");
var year = Console.ReadLine();
friends[i] = new Friend
{
Name = name,
Phone = phone,
Month = Convert.ToInt32(month),
Day = Convert.ToInt32(day),
Year = Convert.ToInt32(year)
};
}
Array.Sort(friends);
for (int x = 0; x < 8; ++x)
{
Console.Write("{0} {1} {2}{3}{4}", friends[x].Name, friends[x].Phone, friends[x].Month, friends[x].Day, friends[x].Year);
Console.Write("\n");
}
Console.ReadKey();
var findfriends = new Friend();
Console.Write("Enter the name you want for info:");
findname = Console.ReadLine();
for (int x = 0; x < 8; ++x)
{
x = Array.BinarySearch(friends, findname);
Console.Write("{0} {1} {2}{3}{4}", friends[x].Name, friends[x].Phone, friends[x].Month, friends[x].Day, friends[x].Year);
}
}
}
class Friend : IComparable
{
public string Name { get; set; }
public string Phone { get; set; }
public int Month { get; set; }
public int Day { get; set; }
public int Year { get; set; }
public Friend()
{ }
int IComparable.CompareTo(Object o)
{
Friend temp = (Friend)o;
return String.Compare(this.Name, temp.Name);
}
}
}
The issue is that you are trying to do a binary search on an array of type Friend to look for a String value. So when your ICompare implementation tries to cast the name to type friend it throws the exception you are seeing. To correctly use the ICompare you would need to create a new temporary friend object to pass into the binary search but just set the name like so:
Array.BinarySearch(friends, new Friend(){ Name = findName });
When you're calling
x = Array.BinarySearch(friends, findname);
you're passing findname, it is string. Here:
Friend temp = (Friend)o;
you're trying to cast this string to the Friend class.