0

i'm trying to write a generic function which should be able to parse a xml file

here is the code

public struct XmlArg
{
    public string Name;
    public Type T;
    public object Value;
};

static bool ParseXmlArgs(XmlReader xml, params XmlArg[] args)
{
    for (int i = 0; i < args.Length; ++i)
    {
        if (xml.MoveToContent() != XmlNodeType.Element || xml.Name != args[i].Name)
        {
            return false;
        }
        args[i].Value = xml.ReadElementContentAs(args[i].T, null);
    }
    return true;
}

static void Main(string[] args)
{
    int a = 0;

    ParseXmlArgs(
        XmlTextReader.Create("C:\\Users\\Yazilim\\Desktop\\XML.xml"),
        new XmlArg[]{
            new XmlArg() { Name = "ErrorCode", T = typeof(int), Value = a}});
}

i know that i should pass a's pointer to Value ( it's type should be some different type other than object of course )

but i don't want it to be non-managed way.

is there any managed way to use a variable's pointer in structure ?

( the function may be wrong or incorrect, and it's not the point )

3
  • I'm not at all clear on what you're asking here. There's no guarantee that any particular variables have something associated with them that would be described as a "pointer". Oct 29, 2014 at 8:40
  • A field of type object contains a reference to that object, so it probably is already what you refer to as a pointer. It works for structs (and primitive types) such as int too through boxing. Oct 29, 2014 at 8:45
  • And you should probably look into generics too. Oct 29, 2014 at 8:49

2 Answers 2

1

Short answer: create an array, pass it to a method, and then read its contents afterwards:

You need to construct the XmlArg[] array before calling the method, and forget about the a variable until the parsing if finished:

var reader = XmlTextReader.Create("C:\\Users\\Yazilim\\Desktop\\XML.xml");
var results = new []
{
    new XmlArg() { Name = "ErrorCode", T = typeof(int) },
    new XmlArg() { Name = "ErrorMessage", T = typeof(string) }
};

if (ParseXmlArgs(reader, results) == true)
{
    // results were passed by reference, so do something with these values
}

Long answer:

A variable of a reference type (which is any class in .NET) contains a reference to its data, where the data is allocated at a different place in memory, along with additional information about the type. Contrary to that, a variable of a value type (like int, float, or any struct) contains the actual value - all the data is contained in that variable, and there exists no other metadata.

When you pass a value type variable as a parameter by value (which is the default way of passing parameters in .NET) to a method, a shallow copy of that value is made. This means that all the data, no matter how large your struct may be (in this case, it's only an int) gets copied, and anything that happens to the value inside the method won't have any effect on the initial value. On the other hand, if you pass a reference type variable by value to a method, the method gets a copy of the reference (which is essentially a pointer), but the original data which the reference points to doesn't get copied, meaning that the copied reference inside the method still points to the one and only object instance, and anything that the method does to the data is reflected outside the method.

Using the ref parameter, you can make a method accept its parameters by reference. Passing a value type by reference will create a reference to the original value, without copying the data, similar to what happens when you pass a reference type by value. In this case, modifying the referenced value inside the method modifies the original value in the variable outside the method, since no copy of the original data was made. If you pass a reference type by reference using the ref keyword, then you are actually passing a reference to the reference to the actual data, meaning that the method now gets the opportunity to even make the original variable point to a completely different object (apart from modifying the original one.

Additionally, casting a value type to an object (which happens when you assign it to the XmlArg.Value property), boxes the value. Boxing the value type again creates a copy of the value somewhere else in memory, and creates a reference type (an object) pointing to that copy. Again, the "link" to the original value is lost, meaning that anything done with that object from that point on cannot possible have any effect on the original variable.

So, in your case, you essentially have:

// a value type variable
int a = 0; 

// implicit boxing occurs, creating a copy of the value
// ("link" to a is lost)
object boxed_a = (object)a;

// a value type (struct) variable which contains a member which points
// to the boxed int value 0
XmlArg arg = new XmlArg() { Value = boxed_a };

// here, you are creating an array of XmlArg, but since XmlArg is a struct, 
// the array actually contains a *copy* of the `arg` value
// ("link" to arg is also lost)
XmlArg[] args = new [] { arg };

One thing that might help in cases like this is variable closure in lambdas. Essentially, using a variable inside an anonymous method creates an actual reference to the original value, which allows you to modify it from anywhere - but the real reason is that the compiler actually places you original value as a field inside the anonymous class created for the lambda: essentially, it's no longer a plain old local variable, and this allows the lambda to work on the original data.

In your case, you would do something like:

// define a common interface (Value is an object)
interface IXmlArg
{
    string Name { get; }
    Type Type { get; }
    object Value { get; set; }
}

// I used generics to get type safety and to get type T information "for free"
class XmlArg<T> : IXmlArg
{
    public XmlArg(string name, Action<T> setter, Func<T> getter)
    {
        _name = name;
        _setter = setter;
        _getter = getter;
    }

    private readonly string _name;
    public string Name { get { return _name; } }

    public Type Type { get { return typeof(T); } }

    private readonly Func<T> _getter;
    private readonly Action<T> _setter;
    public object Value
    {
        get { return (object)_getter(); }
        set { _setter((T)value); }
    }
}

And in you main method, you would do:

// local value type variable
int a = 0;

// we are creating two lambdas, one to set the value to a, and one to read it
IXmlArg arg = new XmlArg<int>("ErrorCode", x => a = x, () => a);

// this method will use the `Value` setter, which in turns calls the lambda
ParseXmlArgs(reader, new [] { arg });
2
  • I wouldn't start your answer as you have. People are frequently confused by the difference between reference types (and the fact that their variables contain references) and the concept of pass by reference, which is what the ref keyword is for. Note that it even says "Do not confuse the concept of passing by reference with the concept of reference types. The two concepts are not the same" Oct 29, 2014 at 9:01
  • @Damien_The_Unbeliever: you're right, I'll rephrase it.
    – vgru
    Oct 29, 2014 at 9:07
0

Note that your struct XmlArg is a mutable value-type which is considered "evil" by many.

Maybe you want the Value member to be a reference to a type with an integer that can change? If you write:

public class ChangeableInt32    // 'class' gives a reference type
{
    public int Content;
}

public struct XmlArg
{
    public string Name;
    public Type T;
    public ChangeableInt32 Value;
}

then:

        args[i].Value.Content = /* read the int */;

Your Answer

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