mehmetaliertorer
mehmetaliertorer

Reputation: 11

Can I use string variable to name an object (C#)?

I am a beginner and currently working on a project for practice. My goal is to create an Adress Book application. What I want to do is I am asking the user to pass in a name. And I store that name in a variable. Is it possible for me to use that string variable to name the object? I have looked for solutions and they all suggest to have a Constructor that takes a name and assigns it but I already have that and it is not what I want. I am storing all these Person variables in a Person List(That's why I am using the loop) and later, I want to build a system to browse through Adress Book and search for stuff. So my overall question is- Can I use a string variable to name the object. Is there any way to do that?

while (true)
{
    Console.WriteLine("Please enter names to the adress book or type \"quit\" to finish");
    var input = Console.ReadLine();
    var name = input;
    if (string.IsNullOrEmpty(input))
    {
        throw new IsNullException("Name can not be null or empty");
    }
    if (input.ToLower() == "quit")
    {
        break;
    }
    Person person = new Person(input);
    AdressBook.Add(person);
}

Upvotes: 0

Views: 1306

Answers (3)

Knowledge Cube
Knowledge Cube

Reputation: 1010

I have looked for solutions and they all suggest to have a Constructor that takes a name and assigns it but I already have that and it is not what I want.

Can you explain why this isn't what you want? It is common and natural in .NET to give names to objects in this way. You could just write your Person class like this:

class Person
{
    private string _name;

    public Person(string input)
    {
        _name = input;
    }

    public string Name
    {
        get
        {
            return _name;
        }
        set
        {
            _name = value;
        }
    }
}

...and then access the object's name by calling its Person.Name property:

var somePerson = new Person("Bob");
Console.WriteLine(somePerson.Name);

In fact, this basically is how individual controls in Windows Forms are assigned names.

Furthermore, assuming your AdressBook variable is declared as a List<Person>, then you can access an individual person's name like this:

// Get the name of the third person added to the AdressBook list.
Console.WriteLine(AdressBook[2].Name);

If for some reason you're not making clear you want to store each Person object's name separately from the object itself, then the Dictionary<string, Person> approach mentioned in Aasmund's answer is perfectly fine. Another option to explore if you really want to stick with the List container type could maybe be a List<Tuple<string, Person>> variable using the .NET Tuple(T1, T2) type.

Without more detail on your requirements, there are dozens of ways you could do this.

Upvotes: 0

MarkPflug
MarkPflug

Reputation: 29498

I suspect that you are looking for Dictionary<TK,TV>. You can use a dictionary to map from a string to any object you like:

// create the dictionary to hold your records.
var records = new Dictionary<string,AddressRecord>();
var item = new AddressRecord("Mary", "Smith", "1234 N Park Ln", "Springfield", "OH");
var key = item.FirstName + " " + item.LastName;
records.Add(key, item);

// try to find someone by name
AddressRecord record;
var key = "Mary Smith";
if(records.TryGetValue(key, out record)) {
   // use the record
   Console.WriteLine("The address for "+ key + " is " + record.Address);

} else {
  Console.WriteLine("No record found for " + key);
}

// or iterate over all the records:
foreach(var record in records.Values) {
    Console.WriteLine(record.FirstName + " " record.LastName);       
}

Of course the dictionary requires that all of it's keys are unique, so you might have problems if you know more than one person named Jon Smith.

Upvotes: 0

Aasmund Eldhuset
Aasmund Eldhuset

Reputation: 37940

No. A variable name is a convenience to the programmer, but it conveys no information to the program. Also note that a variable is just a reference to an object; it is not "the name of the object" (there might actually be many variables that reference the same object).

However, there are situations in which it is convenient to be able to tie an object to another piece of information in order to be able to look the object up by that information later. The general computer science term for this is a hash table, and in C#, it's called a Dictionary. You use it like this:

var peopleByName = new Dictionary<string, Person>();
string name = Console.ReadLine();
Person person = new Person(name);
peopleByName[name] = person;
Person theSamePerson = peopleByName[name];

theSamePerson, which was obtained by asking peopleByName for the object that is tied to the value of the name variable, will now refer to the same object that was added to the dictionary under that name.

Upvotes: 9

Related Questions