Go4Expert (http://www.go4expert.com/)
-   C# (http://www.go4expert.com/articles/c-sharp-tutorials/)
-   -   Basic Sample of Reflection (http://www.go4expert.com/articles/basic-sample-reflection-t3669/)

shabbir 29Mar2007 17:02

Basic Sample of Reflection
1 Attachment(s)
1. Take a new C# Dll project
2. Add a new windows console application project to the solution
3. Add the following to the Dll project.
Code: CSharp

namespace BasicRefDll
    public class SampleClass
        /// <summary>
        /// Shows the message box
        /// </summary>
        /// <param name="msg"></param>
        public void ShowMessage(string msg)
            MessageBox.Show(msg + " Message Box From the DLL");

4. Add the following code into the Exe application.
Code: CSharp

static void Main(string[] args)
    string dllName = @"BasicRefDll.dll";
    // Assembly name  to load

    string myPath = (Application.StartupPath + Path.DirectorySeparatorChar + dllName);
    //Absolute path to the dll file

    Assembly asmDLL = Assembly.LoadFile(myPath);
    //Dynamically load the assembly

    Object asmObject = asmDLL.CreateInstance(@"BasicRefDll.SampleClass");
    //Instance object from the Assembly.

    MethodInfo theMethod = asmObject.GetType().GetMethod(@"ShowMessage");
    //From asmObject we extract the method we need

    object[] arguments = new object[] { “Reflection Sample” }
    // Arguemnts we need to pass

    theMethod.Invoke(asmObject, arguments);
    // Finaly we fire method imported from the dll

The code is self explanatory with lots of comments and so I dont think I will add anything more here.

You can get the name of the class as well but as this is a basic sample I thought of keeping the things as simple as it could be.

You can download the attachmnet but you need to Keep the dll and executable in the same folder and so you may need to copy the dll file to the executable folder after its compiled. I intended not doing this using the Post Build command.

All times are GMT +5.5. The time now is 17:46.