c# How to store multiple value in Array class constructor? - c#

I am making console app using Array class that has username as object, this is member.cs
Class Member{
public string username;
public Member(){
}
public Member(string username){
username = username;
}
}
And this is my Collection.cs
Class Collection{
static Member[] members = new Member[100];
public void Adduser(){
console.writeLine("username?");
string user_input = console.ReadLine();
members = new Member[]{
new Member(user_input)
};
}
public Member[] get() {
return members;
}
}
but every time the Adduser() functions is called, it only stores one member and keeps updating to a new member, in here I am expecting to have 100 usernames at most.
How should I store multiple values in side the constructor or Array object?
Should I create a new array in member class to store multiple-member?
Even after I implemented index, I get nullexception error in side foreach
public void showMember()
{
var data = record.get();
foreach (var value in data)
{
Console.WriteLine(value.Username);
Console.WriteLine(value.Phonenum);
Console.WriteLine(value.Password);
Console.WriteLine(value.Borrowedmovie);
}
}

that's because you renew the array every time.this might help.
int index=0;
public void Adduser(){
console.writeLine("username?");
string user_input = console.ReadLine();
if(index<members.Length)
{
members[index]=new Member(user_input)
index++;
}
else console.writeLine("overflow");
}
}
also I think it's better if you use list instead of array
static List<Member> members = new List<Member>();
public void Adduser(){
console.writeLine("username?");
string user_input = console.ReadLine();
members.Add(new Member(user_input));
}

Instead of an array you should use an List object.
Class Collection{
static List<Member> members = new List<Member>();
public void Adduser(){
console.writeLine("username?");
string user_input = console.ReadLine();
members.Add(new Member(user_input));
}
}

Use index variable and update it everytime u add an item.
Class Collection{
static Member[] members = new Member[100];
int index = 0;
public void Adduser(){
console.writeLine("username?");
string user_input = console.ReadLine();
members[index] = new Member(user_input);
index++;
}
}

Since array is already instantiated with 100 elements, we can not check length of array to check whether elements exists or not.
Array.length will always give the max length of array since the memory is allocated for 100 elements.
But you can check whether last element exists or not and then you can add the new element.
Below code snippet can help you:
class Member
{
public string _username;
public Member()
{
}
public Member(string username)
{
_username = username;
}
}
class Collection
{
private Member[] members = new Member[100];
private int index = 0;
public void Adduser()
{
Console.WriteLine("username?");
string user_input = Console.ReadLine();
var lastElement = members[members.Length - 1];
if (lastElement != null)
{
Console.WriteLine("members array is already full");
return;
}
members[index] = new Member(user_input);
index++;
}
public void DisplayMembers()
{
foreach (var item in members)
{
if (item != null)
{
Console.WriteLine("UserName {0}", item._username);
}
}
}
}
Following is a code for testing the functionality:
static void Main(string[] args)
{
Collection collection = new Collection();
collection.Adduser();
collection.Adduser();
collection.Adduser();
collection.Adduser();
collection.Adduser();
collection.Adduser();
collection.DisplayMembers();
Console.WriteLine("Start second collection");
Collection collection2 = new Collection();
collection2.Adduser();
collection2.Adduser();
collection2.Adduser();
collection2.Adduser();
collection2.Adduser();
collection2.DisplayMembers();
Console.ReadLine();
}

Related

How to access an array of objects from another class

I'm trying to loop through an array of objects and print their properties from a different class.
My main class is
class Program
{
static void Main()
{
//This to be change to relative path
string Path = #"C:\Users\";
string[] lines = { }; ;
//Reading file
if (File.Exists(Path))
{
lines = File.ReadAllLines(Path);
StudentReport.ReadStudents(lines);
}
else
{
Console.WriteLine("The file does't exist");
}
//Printing Students
PrintStudent.Print(lines.Length);
}
}
I'm using this code to declare the array
public class StudentReport
{
public static void ReadStudents(string[] Lines)
{
//declare an array with the number of students
Student[] studentArray = new Student[Lines.Length];
int StudentCounter = 0;
foreach (string Line in Lines)
{
String[] Student = Line.Split(',');
//Calculating values
string ID = Student[0].PadLeft(10, '0');
string name = Student[1];
//Initialize the object
studentArray[StudentCounter] = new Student
{
FullName = name,
ID = ID,
};
StudentCounter++;
}
}
}
And I'm using this class to construct my student object
class Student
{
public string FullName { get; set; }
public string ID { get; set; }
}
To output the student object properties, I made another class. The problem is that I couldn't access the value of the objects array from my new class.
The class I made for outputting purposes is the following, but I cannot get the values. The error is 'Student does not contain a definition for student array
public class PrintStudent
{
public static void Print(int StudentCounter)
{
for(int i = 0; i > StudentCounter; i++)
{
Console.WriteLine(Student.studentArray[i].FullName);
}
}
}
Your error is Student does not contain a definition for studentArray. This is because your Student class does not have studentArray, only the properties FullName and ID. So accessing Student.studentArray[i] doesn't make sense.
Probably what you want is for ReadStudents to return the studentArray so it doesn't go out of scope by changing the method signature to return the Student[], and calling return studentArray at the end.
Then, you can pass your studentArray to your PrintStudent.Print method in the parameters.
By the way, the for(int i = 0; i > StudentCounter; i++) has a wrong < and will never run (lines.Length which is the StudentCounter will always be >= 0)
You can use studentArray.Length, or a foreach loop to iterate over this array, rather than pass the StudentCounter.

how can I access values stored within a method from other places of a class [duplicate]

This question already has answers here:
Help someone new to C# variables
(5 answers)
Closed 2 years ago.
In my current application while I have been able to implement the required logic that I need I am really stuck when trying to take off the content from the main method and using it from a different method .
My code is as below,
class Program
{
const string path = #"filePath";
static void Main(string[] args)
{
setUpValues();
}
private static void setUpValues()
{
var Content = JsonConvert.DeserializeObject<deploy>(File.ReadAllText(path));
List<Variable> variables = Content.Variables.ToList();
Scopes Scope = Content.ScopeValues;
string Version = null;
List<string> ListOfSelectedItems= new List<string>();
List<string> TempListOfSelectedItems = new List<string>();
List<string> Channels = new List<string>();
foreach (var item in variables)
{
if (item.Name.Equals("version"))
{
Version = item.Value;
}
if (item.Name.Equals("Selected"))
{
TempListOfSelectedItems.Add(item.Value);
}
}
Console.WriteLine("Version " + Version);
Console.WriteLine();
string SelectedItems= TempListOfSelectedItems[0];
ListOfSelectedItems = SelectedItems.Split(',').ToList();
Console.WriteLine();
Console.WriteLine("Selected Modules");
Console.WriteLine();
foreach (var item in ListOfSelectedItems)
{
Console.WriteLine(item);
}
foreach (var item in Scope.Channels)
{
Channels.Add(item.Name);
}
}
}
I want to be able to access the variable string Version , the List of ListOfSelectedItems and the List of channels from outside this method .. I want to use these in another as well . So how can I make these globally accessible ?
Would really appreciate your help on this as I have been stuck here
In order to use variables outside a method, you should declare them as fields of a class. Like this:
class Program
{
const string path = #"filePath";
static deploy Content;
static string Version;
static List<string> ListOfSelectedItems;
static List<string> TempListOfSelectedItems;
static List<string> Channels;
// and others
static void Main(string[] args)
{
setUpValues();
}
private static void setUpValues()
{
Content = JsonConvert.DeserializeObject<deploy>(File.ReadAllText(path));
List<Variable> variables = Content.Variables.ToList();
Scopes Scope = Content.ScopeValues;
Version = null;
ListOfSelectedItems = new List<string>();
TempListOfSelectedItems = new List<string>();
Channels = new List<string>();
foreach (var item in variables)
{
if (item.Name.Equals("version"))
{
Version = item.Value;
}
if (item.Name.Equals("Selected"))
{
TempListOfSelectedItems.Add(item.Value);
}
}
Console.WriteLine("Version " + Version);
Console.WriteLine();
string SelectedItems = TempListOfSelectedItems[0];
ListOfSelectedItems = SelectedItems.Split(',').ToList();
Console.WriteLine();
Console.WriteLine("Selected Modules");
Console.WriteLine();
foreach (var item in ListOfSelectedItems)
{
Console.WriteLine(item);
}
foreach (var item in Scope.Channels)
{
Channels.Add(item.Name);
}
}
}
You have to declare those fields as static because they are used in a static method. After the setUpValues finishes running, you can use those fields inside the Main method as well.
Also, this is not related to the question, but the general code convention in C# is to start methods' names with an uppercase letter (so SetUpValues instead of setUpValues) and to start the local variables' names with a lowercase letter (selectedItems instead of SelectedItems). Obviously, it's ultimately up to you how to name things and which code convention to use.
Create a class with properties that you want to access from other places. Instantiate this class in setUpValues and return this.
public class TestClass
{
public TestClass()
{
this.ListOfSelectedItems = new List<string>();
}
public string Version { get; set; }
public List<string> ListOfSelectedItems { get; set; }
}
And then modify your Main method as:
var myObj = setUpValues();
And then Modify setUpValues to return this:
private static TestClass setUpValues()
{
var Content = JsonConvert.DeserializeObject<deploy>(File.ReadAllText(path));
List<Variable> variables = Content.Variables.ToList();
Scopes Scope = Content.ScopeValues;
string Version = null;
List<string> ListOfSelectedItems = new List<string>();
List<string> TempListOfSelectedItems = new List<string>();
List<string> Channels = new List<string>();
foreach (var item in variables)
{
if (item.Name.Equals("version"))
{
Version = item.Value;
}
if (item.Name.Equals("Selected"))
{
TempListOfSelectedItems.Add(item.Value);
}
}
var retObj = new TestClass();
Console.WriteLine("Version " + Version);
Console.WriteLine();
retObj.Version = Version;
string SelectedItems = TempListOfSelectedItems[0];
ListOfSelectedItems = SelectedItems.Split(',').ToList();
Console.WriteLine();
Console.WriteLine("Selected Modules");
Console.WriteLine();
foreach (var item in ListOfSelectedItems)
{
Console.WriteLine(item);
retObj.ListOfSelectedItems.Add(item);
}
foreach (var item in Scope.Channels)
{
Channels.Add(item.Name);
}
return retObj;
}

How can I iterate through a list with multiple objects from class

I am coding an application for my study, but i'm stuck at this point. I made a class called 'Neighborhood'. This class has a string and an int. In my main code I give the class a value and put it in a list. I now want to loop through my list and get the int out of it (put it in a listbox, or do a calculation). How do I get the int out of the list?
class Wijk
{
private string wijken;
private int tijd;
public string Wijken
{
get { return wijken; }
set { wijken = value; }
}
public int Tijd
{
get { return tijd; }
set { tijd = value; }
}
}
Created the list and the instance of the class.
List<object> Uden = new List<object>();
Wijk Wijkeninput = new Wijk();
Now I value the string and int with a combobox and textbox.
private void wijkAanmaken()
{
Wijkeninput.Wijken = Convert.ToString(cbWijken);
Wijkeninput.Tijd = Convert.ToInt16(tbSnelheid.Text);
Uden.Add(Wijkeninput);
}
For this, instead of having an object list, you can have list containing class objects like
List<Wjik> Uden = new List<Wjik>();
then you can access int as follows:
foreach (Wjik obj in listProgram)
{
int tij = Convert.ToInt32(obj.tijd);
}
First the List can be declared like this:
List<Wijk> Uden = new List<Wijk>();
To iterate over it:
foreach(var item in Uden)
{
var myInt = item.Tijd;
var myString = item.Wijken;
//here do whatever you want with the values
}

Generic class where T : Class clarification

There are semi answer to this question which I have read through thoroughly, as well as all things MSDN about generic classes but I am still having trouble when a generic class inherits from another class: where T: ClassName
For example, here is my generic list class
public class MyGenericList2<T> where T : Person
{
private T[] list;
public MyGenericList2(int size)
{
list = new T[size];
}
public T getItem(int index)
{
T temp = default(T);
temp = list[index];
return temp;
}
public void setItem(int index, T value)
{
list[index] = value;
}
public void DisplayList()
{
for (int i = 0; i < list.Length; i++)
{
Console.Out.WriteLine(list[i]);
}
}
}
It inherits from the person class:
NOTE: It is shortened for clarity sake
public abstract class Person
{
protected string firstName;
// Getters
public string getFirstName()
{
return this.firstName;
}
public void setFirstName(string fname)
{
this.firstName = fname;
}
}
When I try to call it I get an error about trying to convert a string to a {namespace}.Person which I sort of get, in that I am trying to put a string into a 'Person' box, but how does one call the class using this mechanism?
Here is the main method
public static void Main(string[] args)
{
MyGenericList2<Person> studentGeneric = new MyGenericList2<Person>(3);
Student st1 = new Student();
st1.setFirstName("Thor");
studentGeneric.setItem(0, st1); //This does not work
studentGeneric.setItem(1, Person.setFirstName("Odin"); // Does not work
studentGeneric.setItem(2, st1.setFirstName("Slepnir"); // Does not work
studentGeneric.DisplayList();
Console.ReadLine();
}
If I cut out the Where T : Person and use GenericList2<string> it works fine, which makes sense since it is string to string.
Any help would be appreciated
quick clarification Student inherits from Person:
public class Student : Person
{
// Student 1
private string studentID01 = "001";
public string getStudentID01()
{
return this.studentID01;
}
}
First of all I would recommend using public properties for your classes, for example:
public abstract class Person
{
public string FirstName { get; set; }
}
public class Student : Person
{
public string StudentId { get; set; }
}
This means your list code would work like this:
Student st1 = new Student();
st1.FirstName = "Thor";
studentGeneric.setItem(0, st1);
And you can even use this syntax:
studentGeneric.setItem(1, new Student
{
FirstName = "Odin"
});
Additionally, the .Net Framework already provides a really nice set of generic collection classes you can use so you don't really need your MyGenericList2<T> class. For example, the most commonly used class is System.Collections.Generic.List:
var people = new System.Collections.Generic.List<Person>();
people.Add(new Student
{
FirstName = "Odin"
});
Or even using the collection initialiser syntax:
var people = new System.Collections.Generic.List<Person>
{
new Student
{
FirstName = "Odin"
}
});
Finally, the problem you are having with outputting your values to the console is because C# doesn't know what to do with your class so by default outputs the value of student.ToString(). And becaue you haven't told your class what to do with it, it just outputs the name of the type. You can either override ToString or, much simpler just call the getFirstName() method:
Console.WriteLine(list[i].getFirstName());
You are using setItem incorrectly. This method can be used to set the value of elements in the list array in an instance of MyGenericList2 class.
To use the setFirstName method on an instance of the Student class, first use getItem to return the object instance. For example:
public void Main(string[] args)
{
MyGenericList2<Person> studentGeneric = new MyGenericList2<Person>(3);
Student st1 = new Student();
st1.setFirstName("Thor");
studentGeneric.setItem(0, st1);
Student st2 = new Student();
studentGeneric.setItem(1, st2);
studentGeneric.getItem(1).setFirstName("Odin");
Student st3 = new Student();
studentGeneric.setItem(2, st3);
studentGeneric.getItem(2).setFirstName("Slepnir");
studentGeneric.DisplayList();
Console.ReadLine();
}
To display the list contents correctly, replace your DisplayList() method with:
public void DisplayList()
{
for (int i = 0; i < list.Length; i++)
{
if(list[i] != null){
Console.Out.WriteLine("{0}: {1}", i, list[i].getFirstName());
}
else
{
Console.Out.WriteLine("{0}: [NULL]", i);
}
}
}

How to maintain instance number in list of objects

I have a class baseClass, and a list of objects of the baseClass. What i want to achieve is that i have to dynamically assign the instance number to each object in the list. for that what am doing is that use a constructor to do this.
Following is the class definition:
public class baseClass
{
private int _InstanceNumber;
private int _MyIntVal;
private string _MyString;
public string MyString
{
get { return _MyString; }
set { _MyString = value; }
}
public int MyIntVal
{
get { return _MyIntVal; }
set { _MyIntVal = value; }
}
public int MyProperty
{
get { return _InstanceNumber; }
}
public baseClass(int instance)
{
_InstanceNumber = instance;
}
}
The creation of the List of objects is as follows:
int instanceNumber = 0;
List<baseClass> classList = new List<baseClass>();
classList.Add(new baseClass(instanceNumber++) { MyString = "sample1", MyIntVal = 10 });
classList.Add(new baseClass(instanceNumber++) { MyString = "sample2", MyIntVal = 11 });
I know it is not the actual way for creating this. it does not give the index number actually. how can i calculate the instance number?
Consider the following scenario, that am creating another list of objects then it hard to maintain the instance number. or if i create another object(this also be an instance) external to the list.
int instanceNumber = 0;
List<baseClass> anotherClassList = new List<baseClass>();
classList.Add(new baseClass(instanceNumber++) { MyString = "sample1", MyIntVal = 10 });
classList.Add(new baseClass(instanceNumber++) { MyString = "sample2", MyIntVal = 11 });
Updates:
This is my temporary solution for this. i need proper way/ method to maintain instance number
If you want to find the index of item in the list, you should ask it from the list, not the item like:
var index = list.IndexOf(item);
But it seems that you expect the item to be aware of its position in the list. In order to do this, you should pass the list to the item so it can use it to find its own place in it:
public class Item
{
private List<Item> _containerList;
public Item(List<Item> containerList)
{
_containerList = containerList;
}
public int InstanceNumber
{
get { return _containerList.IndexOf(this); }
}
}
and change your code to:
List<Item> classList = new List<Item>();
classList.Add(new Item(classList ) { ... });
classList.Add(new Item(classList ) { ... });

Categories

Resources