C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Reviews   Communities   Interview   Jobs   Projects   Training   Your Ad Here    
Silverlight Games | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Polls | Revenue Sharing | Lobby | Gift Shop |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...






Resources » Articles » .NET Framework »

Using reflection to find a Type and create an instance


Posted Date: 02 Jul 2004    Resource Type: Articles    Category: .NET Framework
Author: Sathia Murthi N MahalingamMember Level: Bronze    
Rating: 1 out of 5Points: 5



Sample Code

public void FindContainingAssembly(string strName)
{
foreach (System.Reflection.Assembly a in
System.AppDomain.CurrentDomain.GetAssemblies())
{
try
{
string[] strAssemblyName = a.FullName.Split(new char[]{','});
string strNameTemp = strAssemblyName[0] + "." + strName;
if (System.Activator.CreateInstance(a.FullName, strNameTemp) != null)
{

// Creating Instance
Sample a = (Sample)System.Activator.CreateInstance(a.FullName, strNameTemp)

}
}
catch (System.Exception)
{
continue;
}
}


}

Description :

In the above function strName is the Name of the Class in any of the assemly which You passing as a parameter
Ex: Sample

foreach: statement reads all the Assemblies in the Current Domain(Solution)

Assembly's Full name in the following format : "<Assemlyname>, Version=somthing, Culture=something,PublicToken=something"

strNameTemp: Concating <Assemlyname> with the strName(Class Name)

System.Activator.CreateInstance : is Checking the strNameTemp is existing in the Assemply or not , if exist u can create instance of the class dynamically by casting with the class name

I hope this article give u some idea. good luck everybody.



Responses

Author: critic    02 Jul 2004Member Level: Bronze   Points : 0
Can you kindly refine the sample code? What is the purpose of the 'm_ContainingAssembly' ? Please make it more clear.


Author: Sweet Cousin    02 Jul 2004Member Level: Bronze   Points : 0
Thanks man the programme works fine.. and was really helpful.


Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Sign In to add tags.
(No tags found.)

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: Discover your business objects and classes [For those who can't code or design]
Previous Resource: Accessing Multiple ResultSets using DataReader
Return to Discussion Resource Index
Post New Resource
Category: .NET Framework


Post resources and earn money!
 
More Resources



dotNet Slackers

About Us    Contact Us    Privacy Policy    Terms Of Use