1

Hi.
Is there any way, I can refer to an object with any string's value?

Classname person1 = new Classname("John");
Classname person2 = new Classname("Martin");
string getValue = "person1";

I've tried this: Console.WriteLine(getValue.name); and obviously it didn't work. :(
What could I do instead of this?

2
  • Perhaps it is better if you explain what is the problem that you are trying to solve with this approach. Commented Oct 10, 2020 at 10:19
  • Could you explain why you want this? I've never seen anything like this done before and frankly it seems like a bad idea whatever it's for except for maybe code analysis - but again you wouldn't hard code variable names in strings even then. Commented Oct 10, 2020 at 10:22

2 Answers 2

5

You can store your instances of the Classname class into a dictionary under a string key:

using System;
using System.Collections.Generic;

public class Classname
{
    public string Name { get; set; } 
    public Classname(string name) { Name = name; }
}

public static class Program
{
    public static void Main()
    {
        // store class instance under a name to be referenced later
        var dict = new Dictionary<string, Classname>
        {
            ["person1"] = new Classname("John"),
            ["person2"] = new Classname("Martin"),
        };

        Console.WriteLine(dict["person1"].Name);
    }
}

Output:

John

This could make sense if you have 1000s of names and want to retrieve the instance / check duplicates for special Classname instance by its Name in O(1) - you then put them into a dict under the same name as they get constructed with:

var dict = new Dictionary<string, Classname>();

// use your list of names instead here
foreach (var nameNumber in Enumerable.Range(1, 2000))
{
    var name = $"Name_{nameNumber}";
    dict.Add(name, new Classname(name));
}

// dict provides O(1) access and O(1) check if already created 
// an instance with that name


// check if inside, do not retrieve
if (dict.ContainsKey("Name_155"))
    Console.WriteLine("Name_155 already constructed");

// check and retrieve, create + add if not there
var n = "Name_4000"
if (dict.TryGetValue(n, out var inst))
{
    // do smth with inst
}
else
{
    dict.Add(n, new Classname(n));
    inst = dict[n]; 
    // do smth with inst
}

Still feel it is quite a constructed example.

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

Comments

0

You can't. If you want to reference multiple enumerated Objects just create an array or a list with your objects. for example

Classname[] classnames = {new Classname("..."), new Classname("...")};

you can then reference to them as classnames[0] and classnames[1]

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.