14

I have two classs:

Class Gold;
Class Functions;

There is a method ClassGet in class Functions, which has 2 parameters. I want to send the class Gold as parameter for one of my methods in class Functions. How is it possible?

For example:

public void ClassGet(class MyClassName, string blabla)
{
    MyClassName NewInstance = new MyClassName();
}

Attention: I want to send MyClassName as string parameter to my method.

dur
  • 15,689
  • 25
  • 79
  • 125
Amin AmiriDarban
  • 2,031
  • 4
  • 24
  • 32

4 Answers4

24

Are you looking for type parameters?

Example:

    public void ClassGet<T>(string blabla) where T : new()
    {
        var myClass = new T();
        //Do something with blablah
    }
Khan
  • 17,904
  • 5
  • 47
  • 59
17

The function you're trying to implement already exists (a bit different)

Look at the Activator class: http://msdn.microsoft.com/en-us/library/system.activator.aspx

example:

private static object CreateByTypeName(string typeName)
{
    // scan for the class type
    var type = (from assembly in AppDomain.CurrentDomain.GetAssemblies()
                from t in assembly.GetTypes()
                where t.Name == typeName  // you could use the t.FullName as well
                select t).FirstOrDefault();

    if (type == null)
        throw new InvalidOperationException("Type not found");

    return Activator.CreateInstance(type);
}

Usage:

var myClassInstance = CreateByTypeName("MyClass");
Jeroen van Langen
  • 21,446
  • 3
  • 42
  • 57
7

You could send it as a parameter of the type Type, but then you would need to use reflection to create an instance of it. You can use a generic parameter instead:

public void ClassGet<MyClassName>(string blabla) where MyClassName : new() {
  MyClassName NewInstance = new MyClassName();
}
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • Wrong answer...I Want to Send my Class name as string as parameter to my method – Amin AmiriDarban Sep 14 '13 at 21:39
  • 11
    As a string? That's definitely not what you asked for... so, wrong question. ;) Then you would use the `Activator.CreateInstance(typestr, false)` method to create an instance from that string. – Guffa Sep 14 '13 at 21:47
-3
 public void ClassGet(string Class, List<string> Methodlist)
        {
            Type ClassType;
            switch (Class)
            {
                case "Gold":
                    ClassType = typeof(Gold); break;//Declare the type by Class name string
                case "Coin":
                    ClassType = typeof(Coin); break;
                default:
                    ClassType = null;
                    break;
            }
            if (ClassType != null)
            {
                object Instance = Activator.CreateInstance(ClassType); //Create instance from the type

            }

        }
Amin AmiriDarban
  • 2,031
  • 4
  • 24
  • 32