Andrew Truckle
Andrew Truckle

Reputation: 19107

Adding a class to an exceptions "data" property

I have a simple class called Coordinate that holds an X / Y Z value.

I am doing some processing and create an "Exception".

I am populating the ex.Data property with some custom values.

All is well until I try to add "new Coordinate(x/y/z)" into the data property.

The data property holds "objects".

An exception is thrown and it is telling me that I can't add objects that are not "serializable" or something like that.

I decided to add 3 entries to the data property (x/y/z respectively as double values) and all is well.

I don't quite understand what I need to add to my class so I could have added just an instance of the Coordinate variable instead.

Upvotes: 0

Views: 448

Answers (2)

Kritner
Kritner

Reputation: 13765

It might just be as simple as marking your class as Serializable:

[Serializable]
public class Coordinate
{
    // ..
}

Upvotes: 1

Jamiec
Jamiec

Reputation: 136104

To make a class serializable, you use the SerializableAttribute

[Serializable]
public class Coordinate
{
   ...
}

This is the most basic way of marking an object as serialiazable, there are other methods which give you more control over how the object is serialized/deserialized.

When you apply the SerializableAttribute attribute to a type, all private and public fields are serialized by default. You can control serialization more granularly by implementing the ISerializable interface to override the serialization process.

Upvotes: 2

Related Questions