Create New instance of a class, but use a variable value as name..Possible?

And yes, I've searched everywhere, but haven't found any useful.
So i'll start by asking here.

example code..
Error message:
A local variable named 'className' cannot be declared in this scope because it would give a different meaning to 'className', which is already used in a 'parent or current' scope to denote something else

namespace IsThisPossible
{
    class Program
    {
        static void Main(string[] args)
        {
            string name = "olaf";
            newClass(name);
        }
        static void newClass(string className)
        {
            Stuff className = new Stuff();
        }
    }
    class Stuff
    {
    }
}

In line 10 you tell the compiler that className is a string.
In line 12 you tell it that className is Stuff.
That's why you are getting the error you get.

Im really not sure what you are trying to do.
Are you saying you want the name of the variable that stores an instance of your class to be determined at runtime? Thats really not possible..or desirable : /

In your example you set className to "olaf", are you suggesting that after declaring Stuff className = new Stuff() you want to then be able to do something like olaf.DoSomething(); ???

What is it you are hoping to acheive, because i think you are approaching it all wrong

>>Create New instance of a class, but use a variable value as name..Possible?

It sounds to me like you're confusing the Control.Name property with the name of a reference in code. In code the name used to reference controls is just used by the developer in the source code but little else beyond that. It sounds like you're wanting to do something like this:

namespace IsThisPossible
  {
    class Program
    {
      static void Main1(string[] args)
      {
        string name = "olaf";
        newClass(name);
      }
      static void newClass(string className)
      {
        Stuff s = new Stuff(className);
      }
    }
    public class Stuff
    {
      public string Name { get; set; }
      public Stuff() { }
      public Stuff(string Name)
        :this()
      {
        this.Name = Name;
      }
    }
  }

Hopefully one of the three answers on this thread will help you out!

Awesome! Thanks ;D

We are happy you are happy!
Mark this thread as solved if you want to. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.