1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Basic Sample of Reflection

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

  1. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,292
    Likes Received:
    365
    Trophy Points:
    83
    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:
    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:
    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