0

Hey
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
                
 }


Dog.cs:
 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 by qadsia: n/a

3
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by christos312
0

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];

0

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

dogVariable[i].getName()

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

That's how I made it work ;)

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.