1

I'm translating some Java code to C#. The Java code looks something like

public abstract class myClass implements Cloneable, Serializable {

//fields, constructors etc here.
//...
//...

public abstract Object clone(); //an implementation of this is eventually provided 
in a subclass

//...
//...

}

The clone() from the Cloneable interface was implemented and Serializable has no methods so nothing needs to be implemented from there.

In C# my class looks something like this:

public class myClass : ISerializable, ICloneable{

//fields, constructors etc here.
//...
//...

public abstract Object Clone ();

//...
//...

}

As you can see, ICloneable's method was implemented, but in C#, unlike Java's Serializable, ISerializable interface DOES have a method, so I need to implement it. The problem is I am not sure how, since I am translating this code from Java, and this doesn't need to be done there.

Can someone please let me know how to do this in C#?

I know the missing method is GetObjectData, but I have no idea how to implement it, what to pass to it, or what should be inside it, since this is completely missing in the Java equivalent...

avgn
  • 982
  • 6
  • 19

2 Answers2

3

I assume that you haved used the Serializable interface in Java to inform that your class can be serialized. In .Net you should use a [Serializable] attribute for this, ISerializable interface has a bit different meaning.

So in .Net your code should look like this:

[Serializable]
public class myClass : ICloneable
{

    //fields, constructors etc here.
    //...
    //...

    public abstract Object Clone ();

    //...
    //...
}
Paweł Bejger
  • 6,176
  • 21
  • 26
3

In Java, declaring that a class "implements Serializable" marks that class as "Serializable". The Java interface IS the marker.

In C#, you can accomplish the equivalent by marking the class with the .Net "Serializable" attribute:

EXAMPLE:

// A test object that needs to be serialized.
[Serializable()]        
public class TestSimpleObject  {

    public int member1;
    public string member2;
    public string member3;
    public double member4;

    // A field that is not serialized.
    [NonSerialized()] public string member5; 

    public TestSimpleObject() {

        member1 = 11;
        member2 = "hello";
        member3 = "hello";
        member4 = 3.14159265;
        member5 = "hello world!";
    }

See also:

Community
  • 1
  • 1
paulsm4
  • 114,292
  • 17
  • 138
  • 190