Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a Class as parameter for a method? [duplicate]

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.

like image 602
Amin AmiriDarban Avatar asked Sep 14 '13 21:09

Amin AmiriDarban


3 Answers

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();
}
like image 57
Guffa Avatar answered Sep 20 '22 17:09

Guffa


Are you looking for type parameters?

Example:

    public void ClassGet<T>(string blabla) where T : new()
    {
        var myClass = new T();
        //Do something with blablah
    }
like image 22
Khan Avatar answered Nov 04 '22 01:11

Khan


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");
like image 16
Jeroen van Langen Avatar answered Nov 04 '22 02:11

Jeroen van Langen