Basic Sample of Reflection

shabbir's Avatar author of Basic Sample of Reflection
This is an article on Basic Sample of Reflection in C#.
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.
Attached Files
File Type: zip BasicReflectionSample.zip (8.1 KB, 68 views)