There was an error reflecting type… (.NET/C#)

Let’s say you have a C# (or VB.NET) project with namespace “MyProject” and you are trying to serialize a class named “MyClass” and you get the error message: There was an error reflecting type ‘MyProject.MyClass’.

The first thing to check, is that the class which you want to serialize (that save it to disk), contains the [Serializable] attribute.

 

First Thing to Check: The [Serializable] attribute

Example of proper usage of the [Serializable] attribute:

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

namespace MyProject
{
    [Serializable]
    public class MyClass
    {
        public string something;
        
        //NOTE: Something else is still missing, see next example.

    }
}

Even though however you include the [Serializable] attribute in your class as above, there is still something missing.

If you try to serialize the above class, you will still get the error message  “There was an error reflecting type…

 

Second Thing to Check: Is there a Default Constructor for your Class?

So what’s wrong and you still cannot serialize the class?

Well, the answer is quite simple: You need to include in in your class a default constructor, that is a constructor with no parameters.

 


Get Started with .NET Programming Fast and Easy!

Check our online course titled “.NET Programming for Beginners – Windows Forms with C#
(special limited-time discount included in link).

Learn how to implement Windows Forms projects in .NET using Visual Studio and C#, how to implement multithreading, how to create deployment packages and installers for your .NET Windows Forms apps using ClickOnce in Visual Studio, and more! 

Many live demonstrations and downloadable resources included!

.NET Programming for Beginners - Windows Forms with C# - Online Course
(Lifetime Access, Certificate of Completion, Downloadable Resources and more!)

Learn More


 

Code Example that Works

So, if we take the above code example and further modify it, our class will be successfully serialized to disk:

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

namespace MyProject
{
    [Serializable]
    public class MyClass
    {
        public string something;
        
       //Default Constructor
        public MyClass(){
      
    }
   }
}

 

Featured Online Courses:

 

Read Also:

 

Subscribe to our newsletter and stay up to date!

Check out our latest software releases!

Check out Artemakis’s eBooks!

 

Rate this article: 1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)

Loading...

Reference: SQLNetHub.com (https://www.sqlnethub.com)

© 2018 SQLNetHub