Alerik
Alerik

Reputation: 25

C#: Instantiate a Class with String Variable as Name

I was wondering if it is possible to instantiate a class with a string variable as its name in C#. I don't know how else to explain it other than this.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
public class Product
{
    string name;
    decimal cost;

    Product(string _name, decimal _cost)
    {
        name = _name;
        cost = _cost;
    }
}
class Program
{
    static void Main(string[] args)
    {
        string nameForInstantiatedClass = "DellComputer";
        Product nameForInstantiatedClass = new Product("Inspiron", 399.99m);
    }
}
}

Is it possible to do something like this or to the same effect, using a string to declare the name of an instantiated class or is it just impossible to do? Any help is appreciated.

Upvotes: 1

Views: 262

Answers (2)

Dimitris Batsougiannis
Dimitris Batsougiannis

Reputation: 759

One thing that comes to my mind is to use a

 var products = new Dictionary<string,Product>();

and then you can save / retrieve items like this

products.Add(nameForInstantiatedClass, ProductObject);
Product dellComp = products[nameForInstantiatedClass]

Upvotes: 1

Benoit
Benoit

Reputation: 208

I don't know why you want to do that. Is there an other logic for you? You could put the instance in a List or Dictionary like :

Dictionary<String, Product> dict = new Dictionary()
dict.add("DellComputer", new Product("",399.99m);

Upvotes: 0

Related Questions