Hello,
I have a method that populates my class by loading an XML:
public
class MyClass{
public void LoadXML(string xmlFilePath){
MyClass myObj = new MyClass();myObj = (
MyClass)s.Deserialize(reader); // Deserialize and populate my object from an XML file //myObj is properly filled with data return;}
}
Now I just want to call this method from another class, so I simply have:
MyClass testObj = new MyClass();
testObj.LoadXML("myFile.xml");
testObj --> is EMPTY after the function returns...
Here is my question:
How can I make my current instance (testObj) filled with the data... without having to RETURN an object from my method ? (I want my method to return void)
I want it to work similarly to the NET XmlDocument class:
XmlDocument doc = new XmlDocument()
doc.Load(..) //doc is filled with data
How can I do the same thing? Dows Anybody know how to do this?
Thank you very much in advance for any help
Cheers,
AlanPosted Jan 31, 2008, 4:48 PM
You can't assign to the 'this' reference in a class because it's read-only and hence the error. Curiously, you can do this within a struct but that's a different matter. What I had in mind to circumvent this is as follows.
Suppose MyClass has a couple of private fields exposed by public properties. You could then do this:
public class MyClass
{
private int field1;
private string field2;
public int Property1
{
get {return field1;}
set {field1 = value;}
}
public int Property2
{
get {return field2;}
set {field2 = value;}
}
public void LoadXML(string xmlFilePath)
{
MyClass myObj = (MyClass)s.Deserialize(reader); // deserialize to temporary object
this.field1 = myObj.Property1;
this.field2 = myObj.Property2;
myObj = null; // not necessary unless there's further code in the method
// any other code
}
}
BatiPosted Jan 31, 2008, 4:26 PM
First, thanks for your reply.
Can you please, explain what and how to apply your suggestion since my method returns void
If I try to put before my method returns the following I get an error:
this = testObj;
but I get : read only error?
Any idea?
Thanks again in advance
Cheers,
AlanPosted Jan 31, 2008, 3:37 PM
It's not possible to deserialize directly within a class instance method because you can't assign to the 'this' reference.
However, you can do this indirectly by deserializing to another instance of the class as you have done and then individually assigning the values of that instance's fields to the fields of the current instance before the method returns.