0

im really new to C# so please excuse my sloppy code

public Kid(string name, int age, string location)
    {
        this.age = age;
        this.name = name;
        this.location = location;
    }
NAL = Console.ReadLine().Split(',');
Console.WriteLine("Name-{0} Age-{1} Location-{2}", NAL);
string name = "Kid" + NAL[0];
Kid [name] = new Kid(NAL[0], Int32.Parse(NAL[1]), NAL[2]);

i need ^ this to work but i dont understand any of the types can some one help explain this to me

3
  • What is the current issues that you are facing, while running this code? And what you are trying to achieve? Commented Dec 21, 2016 at 4:34
  • i need to up to unlimited KIds to Archive them and i want to have there object name as Kid(kids name). and i dont know how to do it Commented Dec 21, 2016 at 4:44
  • 1
    Short answer is you can't do what you want to do. Longer answer is look into using a Dictionary. MSDN. Commented Dec 21, 2016 at 4:56

2 Answers 2

2

All you need to change is the "Kid" collection.

Dictionary<string, Kid> Kids = new Dictionary<string, Kid>();
Kids[name] = new Kid(NAL[0], Int32.Parse(NAL[1]), NAL[2]);

Using the Dictionary you can retrieve by name, adding an entry with the same name will overwrite the previous entry.

Sign up to request clarification or add additional context in comments.

3 Comments

i used this and every time i
i used this and every time i Console.WriteLine(Kids[name]); it gives me my namespace.KId
That is the default behaviour when you haven't overridden the ToString method on the class. You can either override ToString or write out a particular property value.
1

You can't dynamically name objects like you want to in C#. You can however implement something that meets your needs using a Dictionary.

var kids = new Dictionary<string, Kid>()
kids.Add(name, new Kid(NAL[0], int.Parse(NAL[1]), NAL[2]);

You can then access the Kid named Sam by doing

kids["KidSam"]

This gives you access to what are essentially named Kid objects without the need to name every object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.