How to call variables from a class

This may be a very simple and stupid question for you, but I did not understand this: I am trying to read a long file with different channels (or sources) of data. Each channel has several fields, for example, name, number, date, data type, and then data. I am new to programming, so my first approach (and possibly the wrong one) is to create a class called β€œChannel”, and then when I read the file (using StreamReader), I create a new Channel for class object for each channel. There will be an unknown number of channels, and my problem is that I do not know how to call this data later.

public class Channel { public string name; public int number= 0; //more labels //data... } 

in my code, I wrote something like this (inside the read loop), each new channel:

 ... line=file.ReadLine() myChannel Channel = new Channel(); myChannel.name=line.Substring(10,20) myChannel.number=line.Substring(20,30) ... 

My question is, how can I name this data later (stored in lists for each channel)? Should I provide a different name for each created object?

I tried Google, but I could not find this exact problem. Thanks.

+4
source share
2 answers

As you mentioned, you can have a List your Channel objects, which means you can reference them later.

Something like (declare this outside your loop ):

 List<Channel> channels = new List<Channel>(); 

Then in your loop you can:

 myChannel Channel = new Channel(); myChannel.name=line.Substring(10,20); myChannel.number=line.Substring(20,30); channels.Add(myChannel); //This is where we add it to the list 
+8
source

It’s also good to note:

 channels.Count; // gives you how many myChannel is in the list Console.WriteLine("Name is: " + channels[0].name); // your data back 
+2
source

Source: https://habr.com/ru/post/1479524/


All Articles