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.