Reputation: 15
So basically I have a Job class
public class Job
{
private string id;
private int numBytes;
private int requiredTime;
}
within my main i receive values and create the job
var aJob = new Job();
Queue jobQueue = new Queue();
I want to be able to take the job info out of the queue as a job again
Job test = new Job();
test = (Job)jobQueue.Peek();
however when I print it out I recieve "Job"
Console.WriteLine(test);
I've also recieved a compiler error when I use:
test = jobQueue.Peek();
Error 1 Cannot implicitly convert type 'object' to 'Job'. An explicit conversion exists
(are you missing a cast?)
basically the goal here is to store jobs in a queue and access the job's individual properties.
much thanks!
Upvotes: 0
Views: 715
Reputation: 3269
First, you'll want to use a Queue<Job>
. The non-generic version is for old versions of .Net Framework which you shouldn't use for new code any more.
Second, you can't print the properties (they are not called attributes) of a custom class just by calling Console.WriteLine()
. You'll need to print them individually, like:
Console.WriteLine("Id = {0}", test.id);
Console.WriteLine("numBytes = {0}", test.numBytes);
Console.WriteLine("requiredTime = {0}", test.requiredTime);
Or override the ToString()
method like described by the other answer.
Upvotes: 1
Reputation: 6390
First of all, use a Queue<T>
instead of a Queue
.
Then, override the ToString()
method of your Job
class:
public override string ToString()
{
return string.Format("id: {0}, numBytes: {1}, requiredTime: {2}", id, numBytes, requiredTime);
}
And then, after taking the job info from the queue, use the ToString()
method to print out the information:
Job test = new Job();
test = jobQueue.Peek(); // casting isn't longer necessary, because you use a Queue<T>
Console.WriteLine(test.ToString());
Upvotes: 0
Reputation: 77540
You want to use the generic queue instead:
Queue<Job> jobQueue = new Queue<Job>();
You see "Job" printed because you did not override ToString()
.
Upvotes: 1