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.
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!
(Lifetime Access, Certificate of Completion, Downloadable Resources and more!)
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(){
}
}
}
Artemakis Artemiou is a Senior SQL Server Architect, Author, and a 9 Times Microsoft Data Platform MVP (2009-2018). He has over 15 years of experience in the IT industry in various roles. Artemakis is the founder of SQLNetHub and TechHowTos.com. Artemakis is the creator of the well-known software tools Snippets Generator and DBA Security Advisor. Also, he is the author of many eBooks on SQL Server. Artemakis currently serves as the President of the Cyprus .NET User Group (CDNUG) and the International .NET Association Country Leader for Cyprus (INETA).
This site uses cookies for personalized content and the best possible experience. By continuing to browse this site, you agree to this use. Find out more.