Sturm
Sturm

Reputation: 4125

How to call variables from a class

This could be an extreme easy and silly question for you but I haven't figured it out: I'm trying to read a long file with a different channels (or sources) of data. Each channel has several fields, for example it's name, number, date, data type and then the data. I'm pretty new in programming, so my first approach (and maybe a wrong one) is to create a class named "Channel" and then when I'm reading the file (with StreamReader) I create new object of the class Channel for each channel. There will an unknown number of channels and my problem is that I don't know how to call that data later.

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

in my code I have written something like this (inside the reading loop), every 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 could I call that data later (stored in lists for each channel)? Should I give a different name to each created object?

I've tried google it but I couldn't find this exact issue. Thank you.

Upvotes: 4

Views: 127

Answers (2)

Half_Baked
Half_Baked

Reputation: 340

And also, good to notice:

channels.Count; // gives you how many myChannel is in the list

Console.WriteLine("Name is: " + channels[0].name); // your data back

Upvotes: 2

Mathew Thompson
Mathew Thompson

Reputation: 56449

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

Something like (declare this outside of your loop):

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

Then in your loop you can do:

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

Upvotes: 8

Related Questions