Basic Sample of Reflection

Discussion in 'C#' started by shabbir, Mar 29, 2007.

  1. shabbir

    shabbir Administrator Staff Member

    Jul 12, 2004
    Likes Received:
    Trophy Points:
    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.
    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.
    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:

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice