1

I have a class that I want to construct, by deserializing it from a network stream.

public Anfrage(byte[] dis)
    {
        XmlSerializer deser = new XmlSerializer(typeof(Anfrage));
        Stream str = new MemoryStream();
        str.Write(dis, 0, dis.Length);
        this = (Anfrage)deser.Deserialize(str);
    }

The intention is that I just want to pass the byte[] and have a proper object, rather than using a method in another class.
Now, I know that I obviously cannot do this =. I've read this question and currently am reading the article mentioned in it, but I am not sure wether I'm understanding it correctly.

Is my intention clear enough?

Is there a way to do what I want to get done here?

Thank you all.

1
  • 1
    You can assign to this in constructors for value types. It may not have the effect you expect, though. Commented Jan 10, 2014 at 13:16

2 Answers 2

12

You cannot overwrite an object within the class itself by assigning to this.

You can for example create a method that returns a new instance:

public static Anfrage Create(byte[] dis)
{
    XmlSerializer deser = new XmlSerializer(typeof(Anfrage));
    Stream str = new MemoryStream();
    str.Write(dis, 0, dis.Length);
    return (Anfrage)deser.Deserialize(str);
}

Then you can instantiate one like this:

var anfrage = Anfrage.Create(bytes);
Sign up to request clarification or add additional context in comments.

2 Comments

So there is no way to create a constructor like Anfrage whatev = new Anfrage(byteArrayFromSerialization)?
Yeah you can, but then you'll have to do something like temp = Deserialize() and then copy all values from temp into this. You don't want that.
3

Usually with this problem is dealt with a static non-constructor function returning the Object.

public static Anfrage Create(byte[] dis)
{
    XmlSerializer deser = new XmlSerializer(typeof(Anfrage));
    Stream str = new MemoryStream();
    str.Write(dis, 0, dis.Length);
    return (Anfrage)deser.Deserialize(str);
}

if you want to have a new object and edit it, make the constructor private instead of public and acces it with you static construction function

2 Comments

Are you serious, or just a slow typer? ;-)
sorry, i clicked on Anwer and wrote the code... I always see, that my answer already is written by another guy, just after submitting it :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.