I am a beginner to c#.
I was wondering what you do when you have an array of objects such as:

//assume dog is a class that does something
private Dog[] dogs;
int numberOfDogs = 2;
for (int i = 0; i < numberOfDogs; i++) {
    Console.WriteLine("Please enter your name");
    dogs[i] = dogs[i].GetName();// This is where I get the error Cannot implicitly   convert type 'string' to type DogNames.Dog

 public string GetName(){
      Console.WriteLine("Please enter your name");
      string name = Console.ReadLine();
      return name;

I understand the bug. The type is Dog not string, but how do I get around this?? When it's a string to object I just use .toString or casting (string) but I can't exactly do toObject or toDog? An explanation would be great. I keep getting stuck on this with everything I try to program.

Edited 6 Years Ago by qadsia: n/a

Need to see more of the Dog class. Are you trying to set the name of the dog? Is there something in the Dog class that can hold the name?

Also, your code won't run. The dogs variable, while declared, never has anything assigned to it. You need a new statement right after the int numberOfDogs line, something like this: dogs = new Dogs[numberOfDogs];

Sry if this is not the answer you seek, i am a begginer to C# too but I think i had similar problem with you

private dog[] dogVariable = new dog[3] 

for (int i=0; i<=2;i++)
dogVariable[i] = new dog(); //creates an array with 3 dogs

After this you can go and get the name


I hope to help you and not confuse you more :p

That's how I made it work ;)

This article has been dead for over six months. Start a new discussion instead.