Tied/linked objects/classes in C# like LINQ

c#, class, linked-list, linq, oop

Solution

doc.Element is a method, it returns a reference to the first (in document order) child element with the specified XName.

Consider this example:

public class A
{
    public A()
    {
        this.Bs = new List<B>();

        this.Bs.Add(new B { Name = "a", Value = "aaa" });
        this.Bs.Add(new B { Name = "b", Value = "bbb" });
        this.Bs.Add(new B { Name = "c", Value = "ccc" });
    }

    public List<B> Bs { get; set; }

    public B B(int index)
    {
        if (this.Bs != null && this.Bs[index] != null)
            return this.Bs[index];

        return null;
    }
}

public class B
{
    public string Name { get; set; }
    public string Value { get; set; }
}

Usage:

A a = new A();
var refToA = a.B(0);
refToA.Value = "Some New Value";

foreach (var bs in a.Bs)
    System.Console.WriteLine(bs.Value);

Explanation:

As you can see the B() method returns a reference to a list item in the A class, updating it will change the value in the A.bs list as well, because it's the very same object.

Problem

Maybe it's a newbie question, but could anyone explain me how the tied/linked classes (I don't know their true names) are made? The example can be `LINQ TO XML`. When I have the beneath code: ``` XDocument doc = XDocument.Load("..."); XElement element = doc.Element("root"); element.SetAttribute("NewAttribute", "BlahBlah"); doc.Save("..."); ``` I change only `element` variable (I don't need to update it in `doc` because its referenced). How to create such classes? [edit] I tried @animaonline's code and it works ``` A a = new A(); B b = a.B(0); b.Name = "asd"; Console.WriteLine(a.Bs[0].Name); // output "asd" ``` But tell what's the difference with the code above and below? ``` List<string> list = new List<string>(); list.Add("test1"); list.Add("test2"); var test = list.FirstOrDefault(); test = "asdasda"; Console.WriteLine(list[0]); // output "test1" - why not "asdasda" if the above example works??? ```

Original source

Related problems