Click here to Skip to main content
15,899,475 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all,

I've this code:

Type interfaceType = typeof(ScriptInterface.IBaseScript);

ScriptInterface.IScriptType1 scriptObject = constructor.Invoke(null) as ScriptInterface.IScriptType1;

/*i want to make it more generic such:

(interfaceType) scriptObject = constructor.Invoke(null) as interfaceType; 
*/


How can i create the "scriptObject" below as "interfaceType" type?

Thanks.
Posted

Normally you can use reflection to create an instance by type. Have a look here:
http://msdn.microsoft.com/en-us/library/5b1f63by.aspx[^]

Also, check this:
http://stackoverflow.com/questions/2198989/creating-a-generic-ilist-instance-using-reflection[^]

Good luck!
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 26-Apr-11 16:31pm    
It's pretty easy but does have some delicate aspects, so I decided to present a whole pseudo-code.
Please see my answer.
--SA
First, you need to make sure some type implements the interface you need.
Use System.Type.GetInterface(string) with a parameter typeof(ScriptInterface.IBaseScript).FullName or System.Type.FindInterfaces.

If the interface is implemented, on a next, find out a constructor you expect. It's the best to find all constructors using System.Type.GetConstructors(BindingFlags). For binding flags make sure you use System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic, because you may need to use private or internal constructor as well. It will return you an array of the objects of the type System.Reflection.ConstructorInfo.

Finally, if you find the constructor type you expect (check up the properties of System.Reflection.ConstructorInfo to find out you have the constructor with the signature you can use), construct the object using one of the methods System.Reflection.ConstructorInfo. It will return you an object. You need to type cast it to ScriptInterface.IBaseScript so you could use it.

That's it!

Good luck,
—SA
 
Share this answer
 
Let me try to explain by taking a tiny example here.

public class Sample
{
public Sample()
{
}

public void SampleMethod()
{
Console.WriteLine("This is sample method !");
}
}

main()
{
// Taking a type here.
System.Type type = typeof(Sample);

// Creates an object using reflection
// You can use it in either way
dynamic obj = System.Reflection.Activator.CreateInstance(type, null);

// Access a member
obj.SampleMethod();
}

In above example, We have used Activator.CreateInstance to create an object of particular type and access the members on that type.

Is this an answer to your question?
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900