How do I Instantiate a variable number of objects? (C#) - c#

I'm currently making a program that needs to do read input from a file (using File.ReadAllLines() ), and I want to create an object for each of those lines. The problem I have is that (number of lines in) the file can obviously change often, so the number of objects I need to instantiate is not known by the compiler.
So for example:
string str[] = File.ReadAllLines();
int n = str.Length;
At this point I want to instantiate n objects of a class, how should I do this?

Assuming your class has a constructor to create itself from a string:
var myObjects = str.Select(x => new MyClass(x));
Note that this will not enumerate until you need these objects. If you want to force enumeration you could do:
var myObjects = str.Select(x => new MyClass(x)).ToList();
Example constructor:
public MyClass(string line)
{
//parse the line and set variables of MyClass
}

Related

How do you return an array in a procedure back to the main procedure in C#?

static string readfileName(string[] name)
{
using (StreamReader file = new StreamReader("StudentMarks.txt"))
{
int counter = 0;
string ln;
while ((ln = file.ReadLine()) != null)
{
if (ln.Length > 4)
{
name[counter] = ln;
counter++;
}
}
file.Close();
return name;
}
}
This is the procedure I'm currently trying to return the array name[50] but the compile time error I can't fix states
"Error CS0029 Cannot implicitly convert type 'string[]' to 'string' "
You don't need to. Your main method passed the array to this method, this method filled it. It doesn't need to hand it back because the object pointed to by your 'name` variable is the same object as pointed to by the original variable in the main method; your main method already has all the array data:
static void Main(){
var x = new string[10];
MyMethod(x);
Console.Write(x[0]); //prints "Hello"
}
static void MyMethod(string[] y){
y[0] = "Hello";
}
In this demo code above we start out with an array of size 10 that is referred to by a variable x. In memory it looks like:
x --refers to--> arraydata
When you call MyMethod and pass x in, c# will create another reference y that points to the same data:
x --refers to--> arraydata <--refers to-- y
Now because both references point to the same area of memory anything that you do with y, will also affect what x sees. You put a string (like I did with Hello) in slot 0, both x and y see it. When MyMethod finishes, the reference y is thrown away, but x survives and sees all the changes you made when working with y
The only thing you can't do is point y itself to another different array object somewhere else in memory. That won't change x. You can't do this:
static void MyMethod(string[] y){
y = new string[20];
}
If you do this your useful reference of x and y pointing to the same area of memory:
x ---> array10 <--- y
Will change to:
x ---> array10 y ---> array20
And then the whole array20 and the y reference will be thrown away when MyMethod finishes.
The same rule applies if you call a method that supplies you an array:
static void MyMethod(string[] y){
y = File.ReadAllLines("some path"); //this also points y away to a new array made by ReadAllLines
}
It doesn't matter how or who makes the new array. Just remember that you can fiddle with the contents of an object pointed to by y all you like and the changes will be seen by x, but you can't change out the entire object pointed to by y and hope x will see it
in that case you WOULD have to pass it back when you're done:
static string[] MyMethod(string[] y){
y = new ...
return y;
}
And the main method would have to capture the change:
Main(...){
string[] x = new string[10];
string[] result = MyMethod(x);
}
Now, while I'm giving this mini lesson of "pass by reference" and "pass by value" (which should have been called "pass by original reference" and "pass by copy of reference") it would be useful to note that there is a way to change things so MyMethod can swap y out for a whole new object and x will see the change too.
We don't really use it, ever; there is rarely any need to. Just about the only time it's used is in things like int.Parse. I'm telling you for completeness if education so that if you encounter it you understand it but you should always prefer a "change the contents but not the whole object" or a "if you make a new object pass it back" approach
By marking the y argument with the ref keyword, c# wont make a copy of the reference when calling the method, it will use the original reference and temporarily allow you to call it y:
static void MyMethod(ref string[] y){
y = new array[20];
}
Our diagram:
x ---> array10data
Temporarily becomes:
x a.k.a y ---> array10data
So if you point y to a new array, x experiences the change too, because they're the same reference; y is no longer a different reference to the same data
x a.k.a y ---> array20data
Like I say, don't use it- we always seek to avoid it for various reasons.
Now, I said at the start "you don't need to" - by that, and for the reasons above, I meant you don't need to return anything from this method
Your method receives the array it shall fill (from the file) as a parameter; it doesn't make a new array anywhere so there isn't any need to return the array when done. It will just put any line longer than 4 chars into an array slot. It could then finish without returning anything and the method that called this method will see the changes it made in the array. This is just like my code, where MyMethod changes slot 0 of the array, MyMethod was declared as void so it didn't need to make a return statement , and my Main method god could still see the Hello that I put in the array. In the same vein, your Main method will see all those lines from the file if you make your ReadFileName method (which should perhaps be called FillArray) because it fills the array called name
The most useful thing your method could return is actually an integer saying how many lines were read; the array passed in is of a fixed size. You can't resize it because that entails making a new array which won't work for all those reasons I talked about above. If you were to make a new array and return it there wouldn't be any point in passing an array in.
There are thus several ways we could improve this code but to my mind they come down to two:
don't pass an array in; let this method make a new array and return it. The new array passed back can be exactly sized to fit
keep with the "pass an array in" idea and return an integer of how many lines were actually read instead
For the second idea (which is the simplest to implement) you have to change the return type to int:
static int ReadFileName(string[] name)
And you have to return that variable you use to track which slot to put the next thing in, counter. Counter is always 1 greater than the number of things you've stored so:
return counter - 1;
Your calling method can now look like:
string[] fileData = new string[10000]; //needs to be big enough to hold the whole file!
int numberOfLinesRead = ReadFileName(fileData);
Can you see now why ReadFileName is a bad name for the method? Calling it FillArrayFromFile would be better. This last line of code doesn't read like a book, it doesn't make sense from a natural language perspective. Why would something that looks like it reads a file name (if that even makes sense) take an array and return an int - calling it ReadFileName makes it sound more like it searches an array for a filename and returns the slot number it was found in. Here ends the "name your methods appropriately 101"
So the other idea was to have the Read method make its own array and return it. While we are at it, let's call it ReadFileNamed, and have it take a file path in so it's not hard coded to reading just that one file. And we will have it return an array
static string[] ReadFileNamed(string filepath)
^^^^^^^^ ^^^^^^^^^^^^^^^
the return type the argument passed in
Make it so the first thing it does is declare an array big enough to hold the file (there are still problems with this idea, but this is programming 101; I'll let them go. Can't fix everything using stuff you haven't been taught yet)
Put this somewhere sensible:
string lines = new string[10000];
And change all your occurrences of "name" to be "lines" instead - again we name our variables we'll just like we name our methods sensibly
Change the line that reads the fixed filename to use the variable name we pass in..
using (StreamReader file = new StreamReader(filepath))
At the end of the method, the only thing left to do is size the array accurately before we return it. For a 49 line file, counter will be 50 so let's make an array that is 49 big and then fill it using a loop (I doubt you've been shown Array.Copy)
string[] toReturn = new string[counter-1];
for(int x = 0; x < toReturn.Length; x++)
toReturn[x] = lines[x];
return toReturn;
And now call it like this:
string[] fileLines = ReadFileNamed("student marks.txt");
If you're looking to return name[50] and you know that will be populated, why not go with:
static string readfileName(string[] name)
{
using (StreamReader file = new StreamReader("StudentMarks.txt"))
{
int counter = 0;
string ln;
while ((ln = file.ReadLine()) != null)
{
if (ln.Length > 4)
{
name[counter] = ln;
counter++;
}
}
file.Close();
return name[50];
}
}
You're getting the error because your method signature indicates that you're going to return a string, but you're defining name as a string[] in the argument. If you simply select a single index of your array in the return statement, you'll only return a string.
You have defined your method to return a string, yet the code inside is returning name, which is a string[]. If you want it to return a string[], then change the signature to specify that:
static string[] ReadFileName(string[] name)
However, since your method is only populating the array that was passed in, it's not really necessary to return the array, since the caller already has a reference to the array we're modifying (they passed it to our method in the first place).
There is a potential problem here, though
We're expecting the caller to pass us an array of the appropriate length to hold all the valid lines from the file, yet that number is unknown until we read the file. We could return an array of the size they specified with either empty indexes at the end if it was too big, or incomplete data if it was too small, but instead we should probably just return them a new array, and not require them to pass one to us.
Note that it's easier to use a List<string> instead of a string[], since lists don't require any knowledge of their size at instantiation (they can grow dynamically). Also, we no longer need a counter variable (since we're using the Add method of the list to add new items), and we can remove the file.Close() call since the using block will call that automatically (one of the cool things about them):
static string[] ReadFileName()
{
List<string> validLines = new List<string>();
using (StreamReader file = new StreamReader("StudentMarks.txt"))
{
string ln;
while ((ln = file.ReadLine()) != null)
{
if (ln.Length > 4)
{
validLines.Add(ln);
}
}
}
return validLines.ToArray();
}
And we can simplify the code even more if we use some static methods of the System.IO.File class:
static string[] ReadFileName()
{
return File.ReadLines("StudentMarks.txt").Where(line => line.Length > 4).ToArray();
}
We could also make the method a little more robust by allowing the caller to specify the file name as well as the minimum line length requirement:
static string[] ReadFileName(string fileName, int minLineLength)
{
return File.ReadLines(fileName)
.Where(line => line.Length >= minLineLength).ToArray();
}
Well, you are trying to do several thing in one method:
Read "StudentMarks.txt" file
Put top lines into name existing array (what if you have too few lines in the file?)
return 50th (magic number!) item
If you insist on such implementation:
using System.Linq;
...
static string readfileName(string[] name)
{
var data = File
.ReadLines("StudentMarks.txt")
.Where(line => line.Length > 4)
.Take(name.Length);
int counter = 0;
foreach (item in data)
if (counter < name.Length)
name[counter++] = item;
return name.Length > 50 ? name[50] : "";
}
However, I suggest doing all things separately:
// Reading file lines, materialize them into string[] name
string[] name = File
.ReadLines("StudentMarks.txt")
.Where(line => line.Length > 4)
// .Take(51) // uncomment, if you want at most 51 items
.ToArray();
...
// 50th item of string[] name if any
string item50 = name.Length > 50 ? name[50] : "";
Edit: Splitting single record (name and score) into different collections (name[] and score[]?) often is a bad idea;
the criterium itself (line.Length > 4) is dubious as well (what if we have Lee - 3 letter name - with 187 score?).
Let's implement Finite State Machine with 2 states (when we read name or score) and read (name, score) pairs:
var data = File
.ReadLines("StudentMarks.txt")
.Select(line => line.Trim())
.Where(line => !string.IsNullOrEmpty(line));
List<(string name, int score)> namesAndScores = new List<(string name, int score)>();
string currentName = null;
foreach (string item in data) {
if (null == currentName)
currentName = item;
else {
namesAndScores.Add((currentName, int.Parse(item)));
currentName = null;
}
}
Now it's easy to deal with namesAndScores:
// 25th student and his/her score:
if (namesAndScores.Count > 25)
Console.Write($"{namesAndScores[25].name} achieve {namesAndScores[25].score}");

How to declare and use a list of string array?

I need to read a line in a file.
Based on the first 3 characters in the file, I can determine a type of record.
This indicates the number of strings the line needs to be split into.
I need to hold all lines of the same type in a List.
How do I do this?
My sample file would look like
123|gf|hf|gr|9
145*gf*43*434*9*645*554
123|grf|fe|yr|9
So all 123 would be in a list of string array type of length 4 like :
public List<string[]> NTE =new List<string[4]>();
Except declaring a length isn't being accepted by the compiler
You could use
List<string[]> NTE =new List<string[]>();
And then as you need to add an element to the NTE, you only need to specify that the size will be 4:
NTE.Add(new string[4]); //here it is defined having size of 4, not in the list declaration
Then when you use it:
NTE[0] = ...something
That is going to be a string[4] array
class ArrayofFour
{
string[] a = new string[4];
public string this[int i]
{
get
{
return a[i];
}
set
{
a[i] = value;
}
}
}
Use the ArrayofFour instead of an array, you can use it like an array using the indexers. This will take care of validation you need.
Then you can have a List<ArrayofFour> NTE = new List<ArrayofFour>();
I think this is what you need or at least help you get there.

c# changes value of one object property from other

I'm creating one object by using values from other object.Like that:
MAP.cs
int[][] map = {......};
Mob m = new Mob(0,0,map);
And calling Mob's class function Move()
m.Move();
Move function looks like this:
int xp = (int)Math.Floor(x / 32);
int yp = (int)Math.Floor(y / 32);
int[] result = lookForClosest(xp, yp);
this.nextX = result[1];
this.nextY = result[0];
map[this.nextY][this.nextX] = 1;
Functions are called using DispatcherTimer in another class(MainWindow)
The result of this application is that map property in MAP class is changed. The only change made should be in the Mob object's map property. Any explanation and possible fix?
Arrays are reference types, so when you call
Mob m = new Mob(0,0,map);
You are passing a reference to the array to the Mob constructor, and any changes you make to the array in the Mob class will be reflected in the source array. You can change this one of two ways:
Clone the array before passing it to the Mob class, or
Clone the array within the Mob constructor.
From a ownership perspective, the question is - should clients expect to see changes to the array, or is the array more of a "seed" input that can be modified within the class?
Also note that you have an array of arrays, so you not only need to close the "outer" array, but each of the arrays within it:
public T[][] Clone<T>(T[][] source)
{
T[][] output = new T[source.Length][];
for(int i=0; i<source.Length; i++)
output[i] = (T[])source[i].Clone();
return output;
}
or if you're comfortable with Linq:
public T[][] Clone<T>(T[][] source)
{
return source.Select(a => (T[])a.Clone()).ToArray();
}

Solution to avoid deep copying in C#

I have a variable var1 which is a customized class that contains a single list of strings. I have another variable var2 which is a list of classes like var1.
What I am aiming to do is I need to iterate over var2, class by class and instantiate AddRange to combine var1s list of string with var2's ith class's own list of string. This is done independently, meaning that var1's list of strings stays the same at each iteration. Only at each iteration will its list of string be combined with that of var2's list of string, but after this iteration, it must revert back to the original. The problem is that I cant get this to work. Each time i add an string, it doesn't revert back.
I've tried making a deep copy and at the end of each iteration setting the intermediate clone class to null. Any ideas?
Below is a rough "PeudoCode"
public void combineString(CustomClass var1)
{
// var2 is a class variable that contains a list of CustomClass
List<CustomClass> finalized = new List<CustomClass>();
for (int i = 0; i < var2.Count; i++)
{
CustomClass tmpVar = (CustomClass)var1.Clone();
tmpVar.addString(var2[i].StringSet); //each Custom class has a stringSet which is a list of strings
// .....Do some analysis of the strings of tmpVar
// if it passes the analysis add tmpVar in to finalize list
// none of the other components should change
if (pass analysis)
{
finalized.Add(tmpVar);
}
tmpVar = null;
}
// When the loop is done, the 'finalized' variable is a list of
// CustomClass but then each element inside finalized contains the same string set.
Console.WriteLine("Done");
}
So, var1 must be unchanged. Either combine the strings into the other var1, or if that one must too be left as is, use a new list all together. I see no need to bother with cloning.
So, you basically have to concatenate two lists of strings in a single string without touching the strings themselves.
Would something like this do for you?
string concatenated = var1.Concat(var2[i].StringSet).Aggregate((item1, item2) => item1 + item2);
Aggregate iterates over an IEnumerable and returns the concatenation of all its items.

Name a list with a combination of previously defined variables in C#?

I'm trying to create a method that names a variable based on a specific set of other variables. For example, I want to create series of Lists (i.e., List1, List2, List3) by named according to two variables. For example:
string l = "List"
int += 1
Such that as I cycled through the code using a foreach loop it would name each List consecutively. Any ideas? I've only gotten this much "correct" so far and its not much:
public static string[] ListRenamer(List<string> list, int num)
{
string x = list.ToString();
string y = num.ToString();
string[] z = new string[1];
return z;
}
I would consider a Dictionary<string,List<string>> instead of separate lists here.
You can then name the keys according to your convention, and it can be done dynamically at runtime.
It is not possible to rename c# variables at runtime since c# is a static language

Categories