Deserialize in constructor

J

jhcorey

I have this method in class Foo:

public Foo DeserializeXML(string sXML)
{
XmlSerializer serializer = new XmlSerializer(typeof(Foo));
StringReader sr = new StringReader(sXML);
return (Foo)serializer.Deserialize(sr);

}

which seems to work fine if I do this:
Foo myFoo = new Foo();
myFoo = myFoo.Deserialize(myXMLString);

I'm trying to figure out if there's a simple way to do the
deserialization in a constructor.

TIA,
Jim
 
J

Joanna Carter [TeamB]

<[email protected]> a écrit dans le message de (e-mail address removed)...

|I have this method in class Foo:
|
| public Foo DeserializeXML(string sXML)
| {
| XmlSerializer serializer = new XmlSerializer(typeof(Foo));
| StringReader sr = new StringReader(sXML);
| return (Foo)serializer.Deserialize(sr);
|
| }
|
| which seems to work fine if I do this:
| Foo myFoo = new Foo();
| myFoo = myFoo.Deserialize(myXMLString);
|
| I'm trying to figure out if there's a simple way to do the
| deserialization in a constructor.

public class Foo
{
// private fields

public Foo(string sXML) : base ()
{
Deserialize(sXML);
}

private void DeserializeXML(string sXML)
{
// assign decoded XML to private fields
}
}

{
Foo myFoo = new Foo(myXMLString);
...
}

Joanna
 
D

David Browne

I have this method in class Foo:

public Foo DeserializeXML(string sXML)
{
XmlSerializer serializer = new XmlSerializer(typeof(Foo));
StringReader sr = new StringReader(sXML);
return (Foo)serializer.Deserialize(sr);

}

which seems to work fine if I do this:
Foo myFoo = new Foo();
myFoo = myFoo.Deserialize(myXMLString);

I'm trying to figure out if there's a simple way to do the
deserialization in a constructor.

Make DeserializeXML static. Then you don't need an instance to call it.

public static Foo DeserializeXML(string sXML)
{

.. . .


Foo myFoo = Foo.Deserialize(myXMLString);


David
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top