C#

Interface Segregation Principle in C# – SOLID Design Principles – Part 4

Posted on Updated on

Overview

In our introduction to the SOLID Design Principles, we mentioned the Interface Segregation Principle as one of the five principles specified. In this post we are going to dive into this design principle with a very simple example in C#.

In the last post on the Liskov Substitution Principle, we utilized the Interface Segregation Principle to refactor our code. The code that we write in this post will be very simple as well and will take that code and introduce another segregation of our interfaces. I generally do not write posts that are “recaps” of previous posts, but our implementation from the last post certainly warrants a “recap” in this one.

The Interface Segregation Principle states that clients (classes) should not be forced to implement interfaces that they do not use. Well this certainly sounds reasonable, doesn’t it?

So if we start with our original design from the Liskov Substitution Principle post, here is our original design and code:

Open Closed Principle

public class Engine
{
    public IgnitionResult Start(IStarter starter)
    {
        return starter.Start();
    }
}

public interface IStarter
{
    string Brand { get; set; }
    string Model { get; set; }
    IgnitionResult Start();
}

public class ElectricStarter : IStarter
{
    public string Brand
    {
        get;
        set;
    }

    public string Model
    {
        get;
        set;
    }

    public IgnitionResult Start()
    {
        //code here to initiate the electric starter
        return IgnitionResult.Success;
    }
}

public class PneumaticStarter : IStarter
{
    public string Brand
    {
        get;
        set;
    }

    public string Model
    {
        get;
        set;
    }

    public IgnitionResult Start()
    {
        //code here to initiate the pneumatic starter
        return IgnitionResult.Success;
    }
}

public class HydraulicStarter : IStarter
{
    public string Brand
    {
        get;
        set;
    }

    public string Model
    {
        get;
        set;
    }

    public IgnitionResult Start()
    {
        //code here to initiate the hydraulic starter
        return IgnitionResult.Success;
    }
}

public enum IgnitionResult
{
    Success,
    Failure
}

In our last post, instead of a single Starter class, we created a distinct type for each type of Starter – electric, pneumatic, and hydraulic. Then we realized that in actual implementation, each type of starter had a different requirement for the object it used to actually work. The ElectricStarter utilized a Battery, the PneumaticStarter utilized an AirCompressor, and the HydraulicStarter utilized a HydraulicPump. When we actually wrote the code needed to make these work, we realized that our single interface just did NOT make sense. See the code below.

public interface IStarter
{
    string Brand { get; set; }
    string Model { get; set; }
    Battery Battery { get; set; }
    AirCompressor Compressor { get; set; }
    HydraulicPump Pump { get; set; }
    IgnitionResult Start();
}

public class ElectricStarter : IStarter
{
    public string Brand
    {
        get;
        set;
    }

    public string Model
    {
        get;
        set;
    }

    public Battery Battery
    {
        get;
        set;
    }

    public AirCompressor Compressor
    {
        get
        {
            throw new NotImplementedException("An Electric Starter does not use an AirCompressor.");
        }
        set
        {
            throw new NotImplementedException("An Electric Starter does not use an AirCompressor.");
        }
    }

    public HydraulicPump Pump
    {
        get
        {
            throw new NotImplementedException("An Electric Starter does not use a HydraulicPump.");
        }
        set
        {
            throw new NotImplementedException("An Electric Starter does not use an HydraulicPump.");
        }
    }

    public IgnitionResult Start()
    {
        //code here to initiate the electric starter
        return IgnitionResult.Success;
    }
}

public class PneumaticStarter : IStarter
{
    public string Brand
    {
        get;
        set;
    }

    public string Model
    {
        get;
        set;
    }

    public Battery Battery
    {
        get
        {
            throw new NotImplementedException("An PneumaticStarter does not use a Battery.");
        }
        set
        {
            throw new NotImplementedException("An PneumaticStarter does not use an Battery.");
        }
    }

    public AirCompressor Compressor
    {
        get;
        set;
    }

    public HydraulicPump Pump
    {
        get
        {
            throw new NotImplementedException("An PneumaticStarter does not use a HydraulicPump.");
        }
        set
        {
            throw new NotImplementedException("An PneumaticStarter does not use an HydraulicPump.");
        }
    }

    public IgnitionResult Start()
    {
        //code here to initiate the pneumatic starter
        return IgnitionResult.Success;
    }
}

public class HydraulicStarter : IStarter
{
    public string Brand
    {
        get;
        set;
    }

    public string Model
    {
        get;
        set;
    }

    public Battery Battery
    {
        get
        {
            throw new NotImplementedException("A HydraulicStarter does not use a Battery.");
        }
        set
        {
            throw new NotImplementedException("A HydraulicStarter does not use an Battery.");
        }
    }

    public AirCompressor Compressor
    {
        get
        {
            throw new NotImplementedException("A HydraulicStarter does not use an AirCompressor.");
        }
        set
        {
            throw new NotImplementedException("A HydraulicStarter does not use an AirCompressor.");
        }
    }

    public HydraulicPump Pump
    {
        get;
        set;
    }

    public IgnitionResult Start()
    {
        //code here to initiate the hydraulic starter
        return IgnitionResult.Success;
    }
}

public class Battery
{
}

public class AirCompressor
{
}

public class HydraulicPump
{
}

public enum IgnitionResult
{
    Success,
    Failure
}

Upon reviewing this code more, it became painfully apparent that it was quite bad and required some refactoring. So, per the Interface Segregation Principle, we broke out the interfaces that we actually needed and went from one interface to four interfaces. As a result, each Starter class implemented its own interface that interface had only what was needed for that type. Nice! Our final code from the last post is below:

public interface IStarter
{
    string Brand { get; set; }
    string Model { get; set; }
    IgnitionResult Start();
}

public interface IElectricStarter : IStarter
{
    Battery Battery { get; set; }
}

public interface IPneumaticStarter : IStarter
{
    AirCompressor Compressor { get; set; }
}

public interface IHydraulicStarter : IStarter
{
    HydraulicPump Pump { get; set; }
}

We picked the interface segregation is our starting point because it sets the stage for the changes that need to be made to the concrete classes.

So then we rewrote our Starter classes to implement their respective interfaces:

public class ElectricStarter : IElectricStarter
{
    public string Brand
    {
        get;
        set;
    }

    public string Model
    {
        get;
        set;
    }

    public Battery Battery
    {
        get;
        set;
    }       

    public IgnitionResult Start()
    {
        //code here to initiate the electric starter
        return IgnitionResult.Success;
    }
}

public class PneumaticStarter : IPneumaticStarter
{
    public string Brand
    {
        get;
        set;
    }

    public string Model
    {
        get;
        set;
    }

    public AirCompressor Compressor
    {
        get;
        set;
    }

    public IgnitionResult Start()
    {
        //code here to initiate the pneumatic starter
        return IgnitionResult.Success;
    }
}

public class HydraulicStarter : IHydraulicStarter
{
    public string Brand
    {
        get;
        set;
    }

    public string Model
    {
        get;
        set;
    }

    public HydraulicPump Pump
    {
        get;
        set;
    }

    public IgnitionResult Start()
    {
        //code here to initiate the hydraulic starter
        return IgnitionResult.Success;
    }
}

And in doing that, we were introduced to the Interface Segregation Principle and used it to help us adhere to another principle. The overlap among the SOLID design principles is so nice!

In the next post, we are going to dive more deeply into the Dependency Inversion Principle. See the links below for all posts related to the SOLID Design Principles.

The SOLID Design Principles
The Single Responsibility Principle (SRP)
The Open-Closed Principle (OCP)
The Liskov Substitution Principle (LSP)
The Interface Segregation Principle (ISP)
The Dependency Inversion Principle (DIP)

 

 

SOLID Design Principles

Posted on Updated on

In software development, principles differ from patterns in the sense that where patterns represent complete, identifiable, repeatable solutions to common problems, principles are objective, factual statements that can be made about code and the manner in which it is constructed and the overall design of an implementation. In other words, patterns refer to code scenarios while principles refer to qualities of code and these qualities are useful in identifying the value of the code.

In this post, we are going to be introduced to Bob Martin’s SOLID design principles. These principles have been around for a long time, and it is immeasurably important for every object-oriented developer to understand them and use them in making day-to-day design decisions. It is not that uncommon to see developers dive into development tasks by writing code first and considering architecture and design second. A good developer though inverts this scenario and considers a sound design before writing the first line of code! This prevents undue code maintenance pain later and allows for the development of better applications through and through.

Consideration of design principles is extremely important throughout a development effort, and failure to make the proper considerations can have a devastating effect on the development of the application and the application’s usefulness, performance, and maintainability.

What are the SOLID Design Principles?

In this section, we are going to outline and briefly discuss each of the five design principles. In subsequent posts we will dive into each principle in more detail. The five SOLID design principles are listed below:

  1. The Single Responsibility Principle (SRP) – this principle states that there should never be more than one reason to change a class. This means also that a given class should exist for one and only one purpose.
  2. The Open-Closed Principle – this principle states that modules should be open for extension but closed for modification. This seems a bit unclear at first until you realize that you can change an object’s behavior by either using abstractions, implementing common interfaces, and from inheritance from common base classes or extending abstract base classes.
  3. The Liskov Substitution Principle – this principle, introduced by Barbara Liskov, simply-stated means that derivative classes have to be substitutable for their base classes. If we think about this for a minute, we can see that this also means that any class that implements a specific interface can be replaced by any other class that implements that interface. In other words, it can be substituted for the original class. Furthermore, a derived class must honor the ‘contract’ set by its super class.
  4. The Interface Segregation Principle (ISP) – this principle states that objects should not be forced to implement interfaces that they do not use. Though this may sound obvious based on the wording, in practice it really means that interfaces should be finely-grained and not specific to the classes for which their implementation is intended.
  5. The Dependency Inversion Principle (DIP) – this principle states that higher-level classes should not depend upon lower-level classes but that both should depend on abstractions. Furthermore, these abstractions should not depend on concrete details but rather on abstractions as well.

Though each principle can be discussed individually, we should understand that no single principle should exist or be applied by itself. They should all be considered as part of the design process. In the following posts, we will dive into each principle in detail and take a look at some simplified code examples that illustrate each one.

The Single Responsibility Principle (SRP)
The Open-Closed Principle (OCP)
The Liskov Substitution Principle (LSP)
The Interface Segregation Principle (ISP)
The Dependency Inversion Principle (DIP)

SOAP Serialization with C# and .NET

Posted on Updated on

In the previous post, we discussed binary serialization with C# and .NET. In this short article we are going to dive into some specific examples of use of the SoapFormatter class to SOAP serialize objects to XML and deserialize from XML back into objects.

We will discuss SOAP a little later in this article 🙂

SOAP Serialization with the SoapFormatter class

To get started, let’s create a simple class, add some attributes to help us control how properties are serialized, then we’ll serialize and deserialize the object.

To get started, let’s create a C# Console Application that we will call SoapSerializationSample.

Create the Soap Serialization Sample Console project
Create the Soap Serialization Sample Console project

Next, we will add a class to the project. We will call this class Sample.

Let’s now add two properties – Name and Value as shown below then decorate the class with the Serializable attribute.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SoapSerializationSample
{
    [Serializable]
    public class Sample
    {
        public string Name
        {
            get;
            set;
        }

        public Int32 Value
        {
            get;
            set;
        }
    }
}

As you can see, this class is very simple and is a great starting point for examining SOAP serialization.

The Serializable attribute signals the .NET runtime that instances of this class can be serialized. To use serialization, this attribute must be in place at the class level.

Before we write the serialization code, let’s first add the references shown in the illustration below:

System.Serialization.Runtime References
System.Serialization.Runtime References

Next, let’s add the following using statements to our Program class:

using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Soap;

In our Program.cs class’s Main() method, we are going to write some simple code that uses the SoapFormatter to serialize an instance of our Sample object into a Soap XML stream.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Soap;

namespace SoapSerializationSample
{
    class Program
    {
        static void Main(string[] args)
        {
            //create an instance of our Sample class
            //which we will serialize below
            Sample sample = new Sample();
            sample.Name = "John Nelson";
            sample.Value = 44;

            //create a FileStream to accept the output
            FileStream fileStream = new FileStream(@"c:\temp\MySoapFile.dat", FileMode.Create);

            //create a SoapFormatter to serialize the object
            SoapFormatter formatter = new SoapFormatter();

            //serialize the object to the .dat file
            formatter.Serialize(fileStream, sample);
        }
    }
}

When we press F5 and run the application, the SoapFormatter serializes the Sample object to our MySoapFile.dat file. If we open this file in Visual Studio, we see something that looks like this:

SoapFormatter XML Output
SoapFormatter XML Output

So, some of you are probably looking at this output and screaming “this is NOT well-formed XML!” and you are right! This file does not contain an xml declaration does not contain opening and closing xml tags. Though an in-depth discussion of SOAP is well beyond the purpose and scope of this article, it will be beneficial to briefly discuss the parts of a SOAP message.

What is SOAP?

Soap is an acronym for Simple Object Access Protocol. It is basically an XML-based protocol for transmitting data between computers and is designed for for data communication via the internet and provides the transport mechanism for web services. SOAP is language and platform independent.

SOAP Message Structure

SOAP messages are encoded as XML documents. These documents begin with a mandatory <Envelope> element and may or may not contain a <Header> element. The <Body> element is mandatory for all SOAP messages, so we would expect to always see that. A <Fault> element may or may not be contained within the <Body> element and is used to provide information about exceptions or errors that may have occurred while the message was processed.

<Envelope> Element

The <Envelope> element is the start and end of the message. The entire SOAP message is contained within the <Envelope> element. Every <Envelope> element must contain exactly one <Body> element – no exceptions! The <Envelope> will change if the version of the message changes.

<Header> Element

<Header> elements are optional within the <Envelope> element and there can be multiple <Header> elements in a SOAP message.

<Body> Element

The <Body> element contains the actual data being transmitted in the SOAP message. You can think of it as the “guts” of the message or the payload of the message.

<Fault> Element

If you have ever worked with WCF, you are familiar with the FaultExceptions. When an error occurs during processing by a web service, information pertaining to that error can be encapsulated within a <Fault> block. If a <Fault> element is included in a SOAP message, there can only be one.

Learning More About SOAP

If you are interested in learning more about the SOAP standard, try this link.

Deserializing with the SoapFormatter

Deserializing with the SoapFormatter is as simple as serializing. See the code below:

//create a FileStream to open the .dat file
FileStream fileStream = new FileStream(@"c:\temp\MySoapFile.dat", FileMode.Open);

//create a SoapFormatter to deserialize the object
SoapFormatter formatter = new SoapFormatter();

//serialize the object to the .dat file
Sample deserializedSample = (Sample)formatter.Deserialize(fileStream);

//show the object properties
Console.WriteLine("The deserialized object:");
Console.WriteLine(String.Format("Name: {0}", deserializedSample.Name));
Console.WriteLine(String.Format("Value: {0}", deserializedSample.Value.ToString()));

Console.Read();

When we press F5 and run our application, we see the values of our object displayed in the console window:

SoapFormatter.Deserialize()
SoapFormatter.Deserialize()

XML Serialization with C# and .NET

Posted on Updated on

In the previous post, we discussed the basics of serialization in .NET. In this short article we are going to dive into some specific examples of use of the XmlSerializer to serialize objects to XML and deserialize from XML back into objects 🙂

XML Serialization with the System.Xml.Serialization.XmlSerializer class

To get started, let’s create a simple class, add some attributes to help us control how properties are serialized, then we’ll serialize and deserialize the object.

To get started, let’s create a C# Console Application that we will call SerializationSample.

Create the Serialization Sample Console Application
Create the Serialization Sample Console Application

Next, we will add a class to the project. We will call this class Sample.

Let’s now add two properties – Name and Value as shown below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SerializationSample
{
    public class Sample
    {
        public string Name
        {
            get;
            set;
        }

        public Int32 Value
        {
            get;
            set;
        }
    }
}

As you can see, this class is very simple and is a great starting point for examining Xml serialization.

In our Program.cs class’s Main() method, we are going to write some simple code that uses the XmlSerializer to serialize an instance of our Sample object into an XML stream.

static void Main(string[] args)
{
    //let's first instantiate our Sample object
    //and set its two properties
    Sample sample = new Sample();
    sample.Name = "John Nelson";
    sample.Value = 44;

    //next, create an instance of an XmlSerializer
    //we will use the Type constructor for this example
    XmlSerializer serializer = new XmlSerializer(typeof(Sample));

    //serialize the object to the Console
    serializer.Serialize(Console.Out, sample);

    Console.ReadLine();
}

When we press F5 and run the console application, our console window displays the resulting XML. See the following illustration.

XMLSerializer.Serialize Output
XMLSerializer.Serialize Output

So when we look at the resulting XML, we see the standard xml declaration followed by the opening tag for our Sample object, an XML namespace (xmlns) attribute, and the values of the two properties in our object. Pretty simple, right?

XML Namespaces

Though my intent in this article is to discuss XML serialization and not XML and its accompanying concepts, we do need to briefly talk about the concept of XML namespaces. XML namespaces provide a couple of things in our generated XML. First, they remove any ambiguity between two or more elements that happen to have the same name. Second, they are useful for grouping elements that relate and adhere to a common “idea” together.

A namespace is identified and conveyed via a uri. So what does that mean? Well, I could define a namespace that I could use for all of my XML “objects” based on http://johnlnelson.com. I could for the sake of this example specify the namespace to be https://johnlnelson.com/namespaces/sample. It is a safe assumption that anyone who produces XML for the purpose of transmitting it via HTTP would do this via a domain, such as johnlnelson.com.

Armed with this little bit of knowledge, let’s modify our code to specify our own namespace and prefix.

static void Main(string[] args)
{
    //let's first instantiate our Sample object
    //and set its two properties
    Sample sample = new Sample();
    sample.Name = "John Nelson";
    sample.Value = 44;

    //next, create an instance of an XmlSerializer
    //we will use the Type constructor for this example
    XmlSerializer serializer = new XmlSerializer(typeof(Sample));

    //specify our namespace
    XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
    namespaces.Add("jln", "https://johnlnelson.com/namespaces/sample");

    //serialize the object to the Console
    //with our specified namespace
    serializer.Serialize(Console.Out, sample, namespaces);

    Console.ReadLine();
}

Pay attention to lines 14-15 and the new overload of the Serialize() method in line 19.

We created an instance of an XmlSerializerNamespaces object and added one prefix/namespace combination. The prefix I chose is “jln” and my namespace is https://johnlnelson.com/namespaces/sample.

When we press F5 to launch the application and view our XML output, we see our own namespace in the XML.

XMLSerializer.Serialize Output with Namespace
XMLSerializer.Serialize Output with Namespace

Pretty simple? Sure it is. Now let’s take a look at the encoding attribute in our xml document tag. What if we don’t want to use the default IBM437 encoding? We can do that too, but the code is slightly more involved (but not too bad).

Let’s modify our serialization code to look like this:

//let's first instantiate our Sample object
//and set its two properties
Sample sample = new Sample();
sample.Name = "John Nelson";
sample.Value = 44;

//next, create an instance of an XmlSerializer
//we will use the Type constructor for this example
XmlSerializer serializer = new XmlSerializer(typeof(Sample));

//specify our namespace
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
namespaces.Add("jln", "https://johnlnelson.com/namespaces/sample");

//create an XmlWriterSettings object to specify the
//encoding and the indentation
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = new UTF8Encoding();
settings.Indent = true;

//create an XmlWriter that utilizes a StringWriter to
//build the output, then write that to the Console window
using (StringWriter stringWriter = new StringWriter())
{
    using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, settings))
    {
        serializer.Serialize(xmlWriter, sample, namespaces);
        Console.Write(stringWriter);
    }
}

Console.ReadLine();

You will see quite a few changes from lines 17 to 30. We will discuss the changes in a bit, but first let’s press F5 and run our code! The console window will now look like this:

XMLSerializer.Serialize() Output
XMLSerializer.Serialize() Output

Okay, so what’s going on here? First, in order to take the level of control over our encoding, we had to initiate the help of a StringWriter and an XmlWriter. We created an XmlWriterSettings object to allow us to specify the encoding and the indentation for our XML output. Then we wrapped the XmlWriter in a StringWriter which we then used to send our output to the Console window.

We won’t go into too much detail about StringWriters and XmlWriters in this article, but let’s just take from this the fact that it is possible to exert varying levels of control over our XML serialization.

Controlling How We Serialize

Before we jump into deserialization, let’s hop back to our Sample class and take a look at some ways we can control how instances of this type are XML serialized. This sample class has two properties: Name and Value. As it stands now, both properties get serialized when we call the XmlSerializer.Serialize() method. Let’s look at some ways we can control this.

System.Xml.Serialization.XmlIgnoreAttribute

Using the XmlIgnore attribute we can instruct the XmlSerializer to ignore public fields or properties when XML serialization takes place. For this example, let’s add an XmlIgnore attribute to the Value property as shown below:

[XmlIgnore]
public Int32 Value
{
    get;
    set;
}

By adding this simple attribute, the XmlSerializer will not serialize this property. Let’s press F5 and give it a try.

When we place a breakpoint and view the XML output in the XML view window, we notice that the Value property did NOT get serialized.

XmlSerializer.Serialize() method with Value property ignored
XmlSerializer.Serialize() method with Value property ignored

Pretty simple, right?

System.Xml.Serialization.XmlElementAttribute

What if we want to serialize a property, but we want the XmlElement to have a name other than the actual name in the object? This is equally simple by decorating that property with an XmlElement attribute. See the code below.

[XmlElement (ElementName="TheValue")]
public Int32 Value
{
    get;
    set;
}

This attribute instructs the XmlSerializer to serialize the property, but to name the XmlElement “TheValue”. Again, we place a breakpoint and view the output:

XmlSerializer.Serialize() method with XmlElement attribute on Value property
XmlSerializer.Serialize() method with XmlElement attribute on Value property

As we can see in the output, the Value field is serialized as TheValue. Pretty simple.

There are more customization options available through attributes, but we are not going to cover all of them here. This MSDN resource is an excellent source of information.

Deserializing XML with C#

Now that we have discussed XML serialization, let’s look quickly at how to deserialize our XML and re-inflate a Sample object.

We will modify the code in our Program class’s Main() method to look like this:

//let's first instantiate our Sample object
//and set its two properties
Sample sample = new Sample();
sample.Name = "John Nelson";
sample.Value = 44;

//next, create an instance of an XmlSerializer
//we will use the Type constructor for this example
XmlSerializer serializer = new XmlSerializer(typeof(Sample));

//specify our namespace
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
namespaces.Add("jln", "https://johnlnelson.com/namespaces/sample");

//serialize the object to a StringWriter
//with our specified namespace
StringWriter writer = new StringWriter();
serializer.Serialize(writer, sample, namespaces);

//for our subsequent deserialization, we will
//get the StringWriter's underlying StringBuilder
string xml = writer.GetStringBuilder().ToString();

//we will create a new StringReader using
//the xml string created above
TextReader reader = new StringReader(xml);

//we will deserialize the reader and cast
//the resulting object to a Sample type
Sample deserialized = (Sample)serializer.Deserialize(reader);

//finally, we will write our object to the Console
Console.WriteLine("We have deserialized our object");
Console.WriteLine(String.Format("Name: {0}", deserialized.Name));
Console.WriteLine(String.Format("Value: {0}", deserialized.Value.ToString()));
Console.WriteLine("That was cool!");

Console.ReadLine();

The commentary in the code is pretty straightforward. We serialized our object into a StringWriter then got that object’s underlying StringBuilder and got its string representation via the xml string object. Then we created a StringReader to utilize the XML string value as an input to our XmlSerializer.Deserialize() method. We immediately cast the return object to the Sample type because we knew that it would work. In most situations like this, should NOT attempt such a cast. Instead, you should stuff the result into an object, then check for null BEFORE attempting the cast. That is just a good programming practice.

When we press F5 to run the application, we see the following output:

XMLSerializer.Deserialize() Output
XMLSerializer.Deserialize() Output

In the next article, we will take a quick look at binary serialization.

Serialization with C# and .NET

Posted on Updated on

What is Serialization?

In the world of software development, serialization is the process of converting an object into a format that allows it to either be persisted (saved) to disk or memory, or to be transmitted across a network or over HTTP or TCP.

An object that has been serialized can be reconstructed later which is known as deserialization. I like to think of deserialization as the process by which we re-inflate the object back into its original state. If you think of an XML web service as an example, an application can be written using standard .NET objects, serialized as XML, passed around via HTTP or TCP, then deserialized (re-inflated) by the receiving application and used further.

In this article, we are going to take a quick look at three forms of .NET serialization and talk briefly about each. The following three articles will address XML serialization, binary serialization, and SOAP serialization and provide walkthroughs that give you an overview of how to implement each.

Serialization in .NET

The .NET Framework provides a few serialization mechanisms. Let’s discuss the three most well-known:

  • XML Serialization – serializes the public fields and properties of an object into an XML stream. XML serialization does not record or preserve information about the object’s original type or namespace. The .NET Framework provides a class called the XmlSerializer. This class provides methods with which we can serialize an deserialize objects.
  • Binary Serialization – serializes an object or an entire hierarchy of objects into a binary format. Binary serialization is a very efficient means of serializing .NET objects. The BinaryFormatter class offers numerous methods allow us to serialize and deserialize objects.
  • SOAP Serialization – serializes an object into XML, but also serializes private members. SOAP serialization does not support serialization of generic collections, but the SoapFormatter saves assembly and type information along with the data itself. SOAP serialization is ideal for communications between heterogeneous applications, or applications that are written using different architectures, languages, platforms, etc.

The decision as to which type to use is dictated by the needs of the application. For example, XML and SOAP serialization produce XML output which is usable across multiple platforms. Binary serialization in .NET should only be used in situations where the objects to be serialized and deserialized reside in namespaces that are usable and referenced by each application. If there is only one application in the discussion, then binary serialization will provide a speedy, compact form of serialization that will be quite suitable. So it comes down to considering performance, storage type and location, and extensibility.

See the table below for a high-level comparison of these three types of .NET serialization.

Comparison of XML Serialization, SOAP Serialization, and Binary Serialization
Comparison of XML Serialization, SOAP Serialization, and Binary Serialization

To use serialization in .NET, you essentially only need two things:

  1. A stream to hold or receive the serialized output
  2. A formatter (XmlSerializer, SoapFormatter, or BinaryFormatter) to fill the stream with output

As we mentioned earlier, XML Serialization utilizes the XmlSerializer class, binary serialization is provided via the BinaryFormatter, and SOAP serialization is handled by the SoapFormatter – .NET provides very rich support for serialization.

.NET Serialization Walkthroughs

The following posts will dive into the specifics of serialization with C# and .NET. Use the links below to select the appropriate post.

XML Serialization in C# and .NET

Binary Serialization in C# and .NET

SOAP Serialization in C# and .NET

System.Reflection – Generic Methods in C# Using Reflection

Posted on Updated on

Generics came on the scene in .NET 2.0 and have been a mainstay ever since! I have developed numerous application frameworks over the years and in every case I have made full use of generics. Very similar to templates in C++, generics allow dynamic type-based operations in a strongly-typed manner and can provide build-time validation. Generics allow us define classes and methods without committing to specific types while we are coding. I am not going to go into a discussion of generics in a general sense since this MSDN resource does a pretty good job of providing a description.

Generic Methods

For our example on to how invoke generic methods via Reflection, we are first going to create a few simple classes whose actual function is a bit nonsensical, but I believe the best way to explain intermediate to advanced concepts is to use simple examples, and thus this is the theme of a large part of my blog :).

  1. To start, using Visual Studio let’s create a new solution that we will call GenericMethodWalkthroughSolution.
  2. Next, let’s add two projects to our solution: a C# Class Library which we will call MyClassLibrary and a C# Console Application which we will call MyConsoleApplication.
  3. In the Console application, add a project reference to MyClassLibrary.
  4. Right-click the MyConsoleApplication project and selected “Set as Startup Project”.

When we are done with these four steps, our Solution Explorer should look like this:

Solution Explorer View with both projects and a project reference added
Solution Explorer View with both projects and a project reference added

Next, we will add four classes to our Class Library project. For fun, I am using classes that you may remember from your very first introduction to Object-Oriented Programming (OOP). Don’t laugh though as they are perfect for this discussion!

The classes are outlined below:

  • Mammal.cs – a class that will be the base class for the remaining two classes.
  • Human.cs – a class that will be instantiated to represent a human.
  • Dog.cs – a class that will be instantiated to represent a dog
  • Manager.cs – a class that will contain a generic method that will create an instance of a human or a dog, generically and a couple of methods that create either specifically.

We will just add a couple of properties to each of the first three then a single generic method to the fourth.

Since the Mammal class is our base class, let’s define a couple of properties that are common to all mammals. How about Weight and Age? Sounds good to me.

Our Mammal class looks like this:

public class Mammal
{
    public Int32 Weight
    {
        get;
        set;
    }

    public Int32 Age
    {
        get;
        set;
    }
}

Our Human class has a couple of properties and inherits Mammal:

public class Human : Mammal
{
    public string Name
    {
        get;
        set;
    }

    public String Occupation
    {
        get;
        set;
    }
}

Our Dog class has a couple of properties and inherits Mammal as well:

public class Dog : Mammal
{
    public String Breed
    {
        get;
        set;
    }

    public Boolean IsLongHaired
    {
        get;
        set;
    }
}

Finally, our Manager class has a single generic method called Create that is generic and accepts any type that inherits Mammal. See the simple code below:

public class Manager
{
    public T CreateMammal<T>()
        where T : Mammal, new()
    {
        return new T();
    }

    public Human CreateHuman()
    {
        return new Human();
    }

    public Dog CreateDog()
    {
        return new Dog();
    }
}

These methods are quite simple, so let’s not focus on their simplicity but focus instead on the concept we’re discussing. The CreateHuman() and CreateDog() methods simply return a new instance of each type. The Create method does the same, but generically and we will move ahead with our examples of how to call generic methods via Reflection.

Let’s return to our Console Application’s Program class and write some code in our static Main() method as shown below.

static void Main(string[] args)
{
    //first, let's just call the methods directly
    Manager manager = new Manager();

    //create a Human
    Human firstHuman = manager.CreateHuman();

    //create a Dog
    Dog firstDog = manager.CreateDog();

    //create a human generically
    Human secondHuman = manager.CreateMammal<Human>();

    //create a dog generically
    Dog secondDog = manager.CreateMammal<Dog>();
}

I included this initial code simply to illustrate normal invocation of each of the methods. Now we are going to invoke each of the methods via Reflection in the code block below.

static void Main(string[] args)
{
    Manager manager = new Manager();
    Type managerType = manager.GetType();

    //invoke the CreateHuman method
    Human human = (Human)managerType.GetMethod("CreateHuman").Invoke(manager, null);

    //invoke the CreateDog method
    Dog dog = (Dog)managerType.GetMethod("CreateDog").Invoke(manager, null);

    //invoke the CreateMammal method and create a Human
    MethodInfo createMammalMethod = managerType.GetMethod("CreateMammal");
    MethodInfo genericCreateMammalMethod = createMammalMethod.MakeGenericMethod(new Type[] { typeof(Human) });
    Human genericHuman = (Human)genericCreateMammalMethod.Invoke(manager, null);

    //invoke the CreateMammal method and create a Dog
    MethodInfo createMammalMethodDog = managerType.GetMethod("CreateMammal");
    MethodInfo genericCreateMammalMethodDog = createMammalMethodDog.MakeGenericMethod(new Type[] { typeof(Dog) });
    Dog genericDog = (Dog)genericCreateMammalMethodDog.Invoke(manager, null);
}

Okay, the last generic method invocations require some discussion. Let’s break out the first generic invocation of the CreateMammal method in the code block below and insert some commentary to provide an explanation.

//invoke the CreateMammal method and create a Human
//As with the other non-generic, Reflection-based invocations in the first two
//methods, we first have to get a reference to the MethodInfo object for the CreateMammal method.
MethodInfo createMammalMethod = managerType.GetMethod("CreateMammal");

//When invoking a generic method, we have to call the MakeGenericMethod method to tell the runtime
//what generic arguments are involved. In this case, we have one argument whose type is Human.
//Therefore, we create a new MethodInfo object that contains the substituted types for the generic argument(s).
MethodInfo genericCreateMammalMethod = createMammalMethod.MakeGenericMethod(new Type[] { typeof(Human) });

//Instead of using the first MethodInfo object we actually invoke the second (generic) one.
Human genericHuman = (Human)genericCreateMammalMethod.Invoke(manager, null);

So the important point here is this: to invoke a generic method via Reflection, you must call the MakeGenericMethod method of the MethodInfo object that holds a reference to the method prior to substitution of the generic arguments. Remember that a generic method may have more than one generic type, so therefore the MakeGenericMethod method accepts an object array that is the collection of generic types.

Now, if we don’t know the generic types at runtime like we did in this example, we can get them through the same MethodInfo object!  See the code block below:

MethodInfo method = managerType.GetMethod("CreateMammal");
if (method.IsGenericMethod == true)
{
    Type[] genericArguments = method.GetGenericArguments();
}

If we place a breakpoint on the fourth line of this block and add a Watch to the genericArguments object we can see for ourselves that the generic type is a type that has a BaseType of Mammal. See below:

Generic Argument Display in Watch Window
Generic Argument Display in Watch Window

 

Related Posts

System.Reflection – Working with the Assembly Class

System.Reflection – Working with the Type Class

System.Reflection – Working with the Type Class

Posted on Updated on

In a previous post, we took a brief look at the System.Reflection.Assembly class. In this post, we are going to move down a level and take a look at the Type class. Every object that resides within a .NET application is a specific Type.

Getting an Object’s Type (Type.GetType() method)

Let’s go ahead and dive in to some code samples that allow us to work with types a little. In the previous post we created a very simple Visual Studio solution that contained a C# Class Library and a C# Console Application. In this post we will add a new class to the console application then from the Program class’s static Main() method we will instantiate our new object. We will work with our new class and add methods to perform certain tasks related to getting Type information.

We will add a new class to the console application and we will name it ‘Person’. Since a person has qualities such as a name, age, height, weight, and so on, we will add a few properties to the class that we will then retrieve and work with via Reflection.

So when we add a few properties and a couple of nonsensical methods to the class, the full code of the Person class looks like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyConsoleApplication
{
    public class Person
    {
        #region Public Properties

        public string Name
        {
            get;
            set;
        }

        public Int32 Age
        {
            get;
            set;
        }

        public Int32 Height
        {
            get;
            set;
        }

        public Int32 Weight
        {
            get;
            set;
        }

        #endregion Public Properties

        #region Public Methods

        public string SayHello()
        {
            return "Hello!";
        }

        public string Speak(string wordsToSpeak)
        {
            return wordsToSpeak;
        }

        #endregion Public Methods
    }
}

To create an instance of a Person, we add the following code to our console application’s Program class’s Main() method:

Person person = new Person();
Type personType = person.GetType();

Now, we will put a breakpoint on the second line shown above and hit F5 to run the console application. When we hit the breakpoint, we will right-click and set a Watch on the personType object. The results are shown below:

Watch window view of the personType object
Watch window view of the personType object

There are more properties of the Type object than I can display in the illustration above but this is more than enough to get us started. If you scan through the property list, you will that there is a lot of information about the type available.

Let’s talk about a few of the more important properties shown.

First, look at the Assembly property. You can see that the value describes the ConsoleApplication assembly, including its version, culture information, public key token (which is null because the assembly is not strongly-named).

Next, the AssemblyQualifiedName shows the same stuff, except the full namespace and type name of the Person object are prepended.

The BaseType property describes the type from which the Person class inherits. In this case, it inherits from System.Object. Had our class inherited another class, the BaseType would reflect that type, and its BaseType would reflect its base type and so on. Ultimately, the lowest level base class would have a BaseType of System.Object. Make sense?

All if the properties that start with Is* are Boolean values that indicate what their names describe.

So far so good? Great! Let’s move on to some things that are a little more interesting.

Getting the Properties within a Type (Type.GetProperties() method)

The Type class’s GetProperties() method allows us to retrieve all properties within a type. This method returns an array of PropertyInfo objects. The PropertyInfo type provides us access to the metadata of a property. Sound confusing? Let’s just dive into some code and clear it up!

Let’s return to our Main() method and add the following code:

Person person = new Person();
Type personType = person.GetType();

//get the PropertyInfo array for all properties
PropertyInfo[] properties = personType.GetProperties();

//create a StringBuilder to hold our formatted output
StringBuilder sb = new StringBuilder();

//iterate the properties and write output
foreach (PropertyInfo property in properties)
{
    sb.AppendLine("================================================================");
    sb.AppendLine(String.Format("Property Name: {0}", property.Name));
    sb.AppendLine("================================================================");

    sb.AppendLine(String.Format("Property Type Name: {0}", property.PropertyType.Name));
    sb.AppendLine(String.Format("Property Type FullName: {0}", property.PropertyType.FullName));

    sb.AppendLine(String.Format("Can we read the property?: {0}", property.CanRead.ToString()));
    sb.AppendLine(String.Format("Can we write the property?: {0}", property.CanWrite.ToString()));
}

string output = sb.ToString();

When we retrieve the string contents of our StringBuilder, we will see the following results:

================================================================
Property Name: Name
================================================================
Property Type Name: String
Property Type FullName: System.String
Can we read the property?: True
Can we write the property?: True
================================================================
Property Name: Age
================================================================
Property Type Name: Int32
Property Type FullName: System.Int32
Can we read the property?: True
Can we write the property?: True
================================================================
Property Name: Height
================================================================
Property Type Name: Int32
Property Type FullName: System.Int32
Can we read the property?: True
Can we write the property?: True
================================================================
Property Name: Weight
================================================================
Property Type Name: Int32
Property Type FullName: System.Int32
Can we read the property?: True
Can we write the property?: True

All of the properties that defined in our Person class are shown here with their data types (both short and full names) and with boolean values that indicate whether they are read-only or write-only properties. The presence of get and set accessors means that our properties are read and write properties. Pretty simple.

Getting and Setting Properties through Reflection

Being able to retrieve our properties is pretty cool, but we can also read values from and write values to our properties using Reflection. Now if we did just simply through the object itself, we could do it very simply like this:

person.Name = "John Nelson";
person.Age = 44;
person.Weight = 240;
person.Height = 70;

Now, to do it via Reflection is still simple, but slightly different. See the code below:

personType.GetProperty("Name").SetValue(person, "John Nelson", null);
personType.GetProperty("Age").SetValue(person, 44, null);
personType.GetProperty("Weight").SetValue(person, 240 , null);
personType.GetProperty("Height").SetValue(person, 70, null);

Okay, this warrants some discussion. To set property values via Reflection, you must use the Type.GetProperty() method, then invoke the PropertyInfo.SetValue() method. The default overload that we used accepts the object in which to set the property value, the value itself, and an object array, which in our example is null. The MSDN resource here explains the overloads of the SetValue() method in more detail.

Now that we’ve set the values using Reflection, let’s get them in the same way. We would do that as shown below:

string name = personType.GetProperty("Name").GetValue(person).ToString();
int age = (int)personType.GetProperty("Age").GetValue(person);
int weight = (int)personType.GetProperty("Weight").GetValue(person);
int height = (int)personType.GetProperty("Height").GetValue(person);

Getting property values is pretty straightforward and easy using Reflection.

Getting the Methods within a Type (Type.GetMethods() method)

In a similar manner to getting the properties within a type, getting and working with methods is pretty simple. For this sample, our methods do not contain generic arguments and I did this to keep the sample simple. We will cover invoking generically-typed methods in a later post.

The following code gets all the methods within our Person type and writes information about each method to a StringBuilder.

Person person = new Person();
Type personType = person.GetType();

//get the methods in the type
MethodInfo[] methods = personType.GetMethods();

//create a StringBuilder to hold our formatted output
StringBuilder sb = new StringBuilder();

//iterate the methods and write output
foreach (MethodInfo method in methods)
{
    sb.AppendLine("================================================================");
    sb.AppendLine(String.Format("Method Name: {0}", method.Name));
    sb.AppendLine("================================================================");

    sb.AppendLine(String.Format("Contains Generic Parameters: {0}", method.ContainsGenericParameters.ToString()));
    sb.AppendLine(String.Format("Is Abstract?: {0}", method.IsAbstract.ToString()));

    sb.AppendLine(String.Format("Is a Constructor?: {0}", method.IsConstructor.ToString()));
    sb.AppendLine(String.Format("Is it Generic?: {0}", method.IsGenericMethod.ToString()));

    sb.AppendLine(String.Format("Is it Private?: {0}", method.IsPrivate.ToString()));
    sb.AppendLine(String.Format("Is it Public?: {0}", method.IsPublic.ToString()));
    sb.AppendLine(String.Format("Is it Static?: {0}", method.IsStatic.ToString()));
    sb.AppendLine(String.Format("Is is Virtual?: {0}", method.IsVirtual.ToString()));

    //if the method is a void, the Return type will be null
    //otherwise, it will return a Type
    if (method.ReturnType != null && !String.IsNullOrEmpty(method.ReturnType.Name))
    {
        sb.AppendLine(String.Format("Return Type: {0}", method.ReturnType.Name.ToString()));
    }

    //there are more properties of the MethodInfo you could output...
}

string output = sb.ToString();

If we execute this code and retrieve the results of the StringBuilder.ToString() method, we will see the following output:

================================================================
Method Name: get_Name
================================================================
Contains Generic Parameters: False
Is Abstract?: False
Is a Constructor?: False
Is it Generic?: False
Is it Private?: False
Is it Public?: True
Is it Static?: False
Is it Virtual?: False
Return Type?: String
================================================================
Method Name: set_Name
================================================================
Contains Generic Parameters: False
Is Abstract?: False
Is a Constructor?: False
Is it Generic?: False
Is it Private?: False
Is it Public?: True
Is it Static?: False
Is it Virtual?: False
Return Type: Void
================================================================
Method Name: get_Age
================================================================
Contains Generic Parameters: False
Is Abstract?: False
Is a Constructor?: False
Is it Generic?: False
Is it Private?: False
Is it Public?: True
Is it Static?: False
Is it Virtual?: False
Return Type: Int32
================================================================
Method Name: set_Age
================================================================
Contains Generic Parameters: False
Is Abstract?: False
Is a Constructor?: False
Is it Generic?: False
Is it Private?: False
Is it Public?: True
Is it Static?: False
Is it Virtual?: False
Return Type: Void
================================================================
Method Name: get_Height
================================================================
Contains Generic Parameters: False
Is Abstract?: False
Is a Constructor?: False
Is it Generic?: False
Is it Private?: False
Is it Public?: True
Is it Static?: False
Is it Virtual?: False
Return Type: Int32
================================================================
Method Name: set_Height
================================================================
Contains Generic Parameters: False
Is Abstract?: False
Is a Constructor?: False
Is it Generic?: False
Is it Private?: False
Is it Public?: True
Is it Static?: False
Is it Virtual?: False
Return Type: Void
================================================================
Method Name: get_Weight
================================================================
Contains Generic Parameters: False
Is Abstract?: False
Is a Constructor?: False
Is it Generic?: False
Is it Private?: False
Is it Public?: True
Is it Static?: False
Is it Virtual?: False
Return Type: Int32
================================================================
Method Name: set_Weight
================================================================
Contains Generic Parameters: False
Is Abstract?: False
Is a Constructor?: False
Is it Generic?: False
Is it Private?: False
Is it Public?: True
Is it Static?: False
Is it Virtual?: False
Return Type: Void
================================================================
Method Name: SayHello
================================================================
Contains Generic Parameters: False
Is Abstract?: False
Is a Constructor?: False
Is it Generic?: False
Is it Private?: False
Is it Public?: True
Is it Static?: False
Is it Virtual?: False
Return Type: String
================================================================
Method Name: Speak
================================================================
Contains Generic Parameters: False
Is Abstract?: False
Is a Constructor?: False
Is it Generic?: False
Is it Private?: False
Is it Public?: True
Is it Static?: False
Is it Virtual?: False
Return Type: String
================================================================
Method Name: ToString
================================================================
Contains Generic Parameters: False
Is Abstract?: False
Is a Constructor?: False
Is it Generic?: False
Is it Private?: False
Is it Public?: True
Is it Static?: False
Is it Virtual?: True
Return Type: String
================================================================
Method Name: Equals
================================================================
Contains Generic Parameters: False
Is Abstract?: False
Is a Constructor?: False
Is it Generic?: False
Is it Private?: False
Is it Public?: True
Is it Static?: False
Is it Virtual?: True
Return Type: Boolean
================================================================
Method Name: GetHashCode
================================================================
Contains Generic Parameters: False
Is Abstract?: False
Is a Constructor?: False
Is it Generic?: False
Is it Private?: False
Is it Public?: True
Is it Static?: False
Is it Virtual?: True
Return Type?: Int32
================================================================
Method Name: GetType
================================================================
Contains Generic Parameters: False
Is Abstract?: False
Is a Constructor?: False
Is it Generic?: False
Is it Private?: False
Is it Public?: True
Is it Static?: False
Is it Virtual?: False
Return Type: Type

This is odd because we only defined two methods for our class, right? Well, it actually makes perfect sense because we retrieve ALL of the methods for the Person Type.

Beginning from the top of the results list, take a look at the methods whose names begin with “get_” and “set_”. It just so happens that properties are implemented in MSIL as methods! The get accessor is actually a method with a name that begins with “get_” and the set accessor is a method that begins with “set_”. So in reality, each of our properties created two (2) methods.

The ToString(), Equals(), GetHashCode(), and GetType() methods are actually inherited from the System.Object class which is the default base class of ALL objects in .NET.

So if we eliminate these methods, we are left with our two public methods, SayHello() and Speak().

Invoking a Method via Reflection

When dealing with non-generic methods, there are two basic ways to invoke them dynamically.

  1. The first approach is to get a reference to the MethodInfo object for the method to be called, then calling the MethodInfo.Invoke(object, object[]) method. With this approach, the first argument is the object within which the method is to be called. In our case the ‘person’ object. The second argument is an object array that accepts the arguments expected by the method in the order they are specified in the method.
  2. The second approach is to Type.InvokeMenber(methodName, Binder, object, object[]) method overload. I chose this overload of the InvokeMember method because it is the simplest and is perfect for illustrative purposes.

So let’s get going with some code to test this out! Let’s stick with our iterative approach to loop through the methods as we did above, but lets add some code that checks to see if the method name is “Speak” or “SayHello”, then invoke the method using Approach #1 first.

If we replace the code with the code listed below (see new lines 32-44):

//get the methods in the type
MethodInfo[] methods = personType.GetMethods();

//create a StringBuilder to hold our formatted output
StringBuilder sb = new StringBuilder();

//iterate the methods and write output
foreach (MethodInfo method in methods)
{
    sb.AppendLine("================================================================");
    sb.AppendLine(String.Format("Method Name: {0}", method.Name));
    sb.AppendLine("================================================================");

    sb.AppendLine(String.Format("Contains Generic Parameters: {0}", method.ContainsGenericParameters.ToString()));
    sb.AppendLine(String.Format("Is Abstract?: {0}", method.IsAbstract.ToString()));

    sb.AppendLine(String.Format("Is a Constructor?: {0}", method.IsConstructor.ToString()));
    sb.AppendLine(String.Format("Is it Generic?: {0}", method.IsGenericMethod.ToString()));

    sb.AppendLine(String.Format("Is it Private?: {0}", method.IsPrivate.ToString()));
    sb.AppendLine(String.Format("Is it Public?: {0}", method.IsPublic.ToString()));
    sb.AppendLine(String.Format("Is it Static?: {0}", method.IsStatic.ToString()));
    sb.AppendLine(String.Format("Is it Virtual?: {0}", method.IsVirtual.ToString()));

    //if the method is a void, the Return type will be null
    //otherwise, it will return a Type
    if (method.ReturnType != null && !String.IsNullOrEmpty(method.ReturnType.Name))
    {
        sb.AppendLine(String.Format("Is is Private?: {0}", method.ReturnType.Name.ToString()));
    }

    if (method.Name == "SayHello")
    {
        object result = method.Invoke(person, new object[] { });
        if (result != null)
        {
            sb.AppendLine(String.Format("***Calling the SayHello() method. The result of the method call is: {0}", result.ToString()));
        }
    }
    else if (method.Name == "Speak")
    {
        object result = method.Invoke(person, new object[] { "How are you today?" });
        sb.AppendLine(String.Format("***Calling the Speak() method. The result of the method call is: {0}", result.ToString()));
    }

    //there are more properties of the MethodInfo you could output...
}

string output = sb.ToString();

When we execute the new code the output for the Speak() and SayHello() methods now includes the results too:

================================================================
Method Name: SayHello
================================================================
Contains Generic Parameters: False
Is Abstract?: False
Is a Constructor?: False
Is it Generic?: False
Is it Private?: False
Is it Public?: True
Is it Static?: False
Is it Virtual?: False
Is it Private?: String
***Calling the SayHello() method. The result of the method call is: Hello!
================================================================
Method Name: Speak
================================================================
Contains Generic Parameters: False
Is Abstract?: False
Is a Constructor?: False
Is it Generic?: False
Is it Private?: False
Is it Public?: True
Is it Static?: False
Is it Virtual?: False
Is it Private?: String
***Calling the Speak() method. The result of the method call is: How are you today?

Pay attention to the lines in blue. We actually called those methods and added the results in a formatted way to our sample output StringBuilder. Pretty simple, right?

Now we take a slightly different approach and simply invoke the method via Reflection by name. This is very straightforward and can be done as shown below:

//invoke the SayHello method
object methodResult = personType.GetMethod("SayHello").Invoke(person, null);
if (methodResult != null)
{
    string thePersonSaid = methodResult.ToString();
}

//invoke the Speak method and pass the string argument in
object methodResult2 = personType.GetMethod("Speak").Invoke(person, new object[] { "I have spoken." });
if (methodResult2 != null)
{
    string thePersonThenSaid = methodResult2.ToString();
}

So now we have looked at a couple of ways to invoke methods via Reflection. One method accepts no arguments and the other accepted a string. What if we had a method that accepted two or more arguments?

Go back to our Person class and add the following method:

public string CallTheChildrenInForDinner(string firstChild, string secondChild)
{
    return String.Format("{0}, {1} it is time for dinner!", firstChild, secondChild);
}

We can invoke this method with the following code:

object methodResult3 = personType.GetMethod("CallTheChildrenInForDinner").Invoke(person, new object[] { "Bobby", "Gene" });
if (methodResult3 != null)
{
    string dinnerCall = methodResult3.ToString();
}

The result of this method call is: Bobby, Gene it is time for dinner!.

Getting the Interfaces Implemented by a Type

Within C#, a class can only inherit one base class (i.e. can only have one BaseType). A class can, however implement multiple interfaces. An interface looks much like a class, but only contains the definitions (signatures) of the public properties, methods, events, and indexers within the class that implements it. When discussing interfaces, we use the term “implements” for any class whose construction is governed by an interface. It is an accepted rule that interface names should generally begin with the letter “I”.

The Type class contains methods that allow us to retrieve interface implementation details for any given type. To take a look at this, let’s add an IPerson interface to our class library project. The code below is the full definition of the IPerson interface:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyConsoleApplication
{
    public interface IPerson
    {
        #region Public Properties

        string Name { get; set; }       

        Int32 Age { get; set; }

        Int32 Height {get; set; }

        Int32 Weight { get; set; }        

        #endregion Public Properties

        #region Public Methods

        string SayHello();

        string Speak(string wordsToSpeak);

        string CallTheChildrenInForDinner(string firstChild, string secondChild);

        #endregion Public Methods
    }
}

Now that we’ve created our interface, let’s flip over to our Person class and implement the interface.

public class Person : IPerson

Now that we’ve done this, let’s modify the code in our Main() method to find the interfaces implemented by the Person type. See the code below:

Person person = new Person();
Type personType = person.GetType();
Type[] interfaces = personType.GetInterfaces();

If we place a breakpoint on the last line of the code above and add a Watch to the interfaces object, we will see the output displayed below:

Watch output for personType.GetInterfaces() method
Watch output for personType.GetInterfaces() method

This shows us that the IPerson interface is implemented by the Person type. If we expand the watch definition for the IPerson type we see all the properties for that that we saw for the Person class. The differences will be in the IsClass and IsInterface properties. Pretty simple.