Click here to Skip to main content
15,879,326 members
Articles / Programming Languages / C# 7.0
Tip/Trick

Using Reflections in C#

Rate me:
Please Sign up or sign in to vote.
4.43/5 (4 votes)
24 Jun 2019CPOL1 min read 11.5K   117   9   9
This article shows how to use reflections in C#.

Introduction

Let’s say we have devices of different model with the same functionality. How to use them in a single project? In this article, we will see creating class libraries for each of these device models and using them in one project with the aid of Reflection technology.

Using the Code

First of all, we create class library project named “DeviceCommon” and we add new interface which includes logic of all devices.

IDevice.cs

C#
/// <summary>
///
/// </summary>
public interface IDevice
{
    /// <summary>
    ///
    /// </summary>
    /// <returns></returns>
    bool Open();

    /// <summary>
    ///
    /// </summary>
    /// <returns></returns>
    bool Reset();

    /// <summary>
    ///
    /// </summary>
    /// <returns></returns>
    DeviceStatus GetStatus();
    void Initialize();

    /// <summary>
    ///
    /// </summary>
    /// <returns></returns>
    string GetModel();
}

Now, we create class library project for each of the device models. Each class library contains different logic and Implementation of IDevice interface which will be invoked from the former project. Below is a suitable code fragment:

This code fragment is for device of model named “Device1”.

Device1.cs

C#
public class Device1 : IDevice
    {
        public string GetModel()
        {
            return "Device1";
        }

        public DeviceStatus GetStatus()
        {
            throw new System.NotImplementedException();
        }

        public void Initialize()
        {
            throw new System.NotImplementedException();
        }

        public bool Open()
        {
            throw new System.NotImplementedException();
        }

        public bool Reset()
        {
            throw new System.NotImplementedException();
        }
    }

This code fragment is for device of model named “Device2”.

Device2.cs

C#
public class Device2 : IDevice
    {
        public string GetModel()
        {
            return "Device2";
        }

        public DeviceStatus GetStatus()
        {
            throw new System.NotImplementedException();
        }

        public void Initialize()
        {
            throw new System.NotImplementedException();
        }

        public bool Open()
        {
            throw new System.NotImplementedException();
        }

        public bool Reset()
        {
            throw new System.NotImplementedException();
        }
    }

Other device library projects also can be created in this way, although the logic they contain will differ.

Now we create main project to use these devices. By reflection, it’s enough to add “DeviceCommon” to project reference in order to use class libraries, because all device models extended from IDevice interface in “DeviceCommon” class library project. This is the power of reflection: Using Interface, we can find all class objects extended from it and we can get access to all their accessible members and methods. For facility, we will create App.config configuration file and add DLL reference to it. It provides the opportunity to re-build the project automatically after release.

App.config

XML
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="DllFileName" value="Device1.dll"/>
  </appSettings>
</configuration>

Code fragment to use in the main project. Included here is code to invoke each class libraries shown in App.config dynamically using reflection:

Program.cs

C#
class Program
    {
        static void Main(string[] args)
        {
            string path = Environment.CurrentDirectory + @"\";
            var dllFileName = ConfigurationSettings.AppSettings["DllFileName"];

            if (dllFileName == null)
                throw new Exception("Dll file not shown in App.config!");

            string fileForLoad = path + dllFileName;
            if (!File.Exists(fileForLoad))
                throw new Exception("Dll file not found!");

            var myAssembly = Assembly.LoadFile(fileForLoad);
            var serviceType = typeof(IDevice);
            var types = myAssembly.GetTypes().ToList();
            var myServiceType = types.Where(w => 
            serviceType.IsAssignableFrom(w)).ToList().FirstOrDefault();
            if (myServiceType == null)
                throw new Exception("Service not found!");

            var myDevice = Activator.CreateInstance(myServiceType) as IDevice;
            Console.WriteLine("Device model: "+myDevice.GetModel());
            Console.ReadKey();
        }
    }

History

  • 24th June, 2019: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Uzcard
Uzbekistan Uzbekistan
I was born in 1983 in Bukhara region of Uzbekistan. I have been living in Tashkent since 2007. I Started Bukhara State University Inrormation Technologies and Mathematics faculty in 2003 and graduated at 2007 as the highest ranking student of the department. I am working as a senior .net/java software developer in Tashkent region of Uzbekistan now

Comments and Discussions

 
QuestionDll file not found Pin
masta971gwada7-Aug-19 5:19
masta971gwada7-Aug-19 5:19 
QuestionWhy not MEF Pin
danzar1011-Jul-19 12:05
danzar1011-Jul-19 12:05 
QuestionExpensive! Pin
David A. Gray25-Jun-19 18:38
David A. Gray25-Jun-19 18:38 
AnswerRe: Expensive! Pin
tbayart28-Jun-19 3:11
professionaltbayart28-Jun-19 3:11 
GeneralRe: Expensive! Pin
David A. Gray28-Jun-19 6:03
David A. Gray28-Jun-19 6:03 
AnswerRe: Expensive! Pin
Mansur Kurtov2-Jul-19 18:06
professionalMansur Kurtov2-Jul-19 18:06 
GeneralRe: Expensive! Pin
David A. Gray3-Jul-19 5:17
David A. Gray3-Jul-19 5:17 
QuestionError ((file not found) Pin
Member 1344593725-Jun-19 8:01
Member 1344593725-Jun-19 8:01 
AnswerRe: Error ((file not found) Pin
AnotherKen26-Jun-19 4:30
professionalAnotherKen26-Jun-19 4:30 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.