LINQ - Does the Where expression return new instance or reference to object instance

后端 未结 5 1815
自闭症患者
自闭症患者 2021-01-31 15:01

This is probably a basic question for some, but it affects how I design a piece of my program.

I have a single collection of type A:

IEnumerable         


        
5条回答
  •  庸人自扰
    2021-01-31 15:17

    The instances are the same if they are classes, but copies if they are structs/value types.

    int, byte and double are value types, as are structs (like System.Drawing.Point and self-defined structs). But strings, all of your own classes, basically "the rest", are reference types.

    Note: LINQ uses the same rules as all other assignments.

    For objects:

    Person p1 = new Person();
    p1.Name = "Mr Jones";
    Person p2 = p1;
    p2.Name = "Mr Anderssen";
    // Now p1.Name is also "Mr Anderssen"
    

    For structs:

    Point p1 = new Point();
    p1.x = 5;
    Point p2 = p1;
    p2.x = 10;
    // p1.x is still 5
    

    The same rules apply when using LINQ.

提交回复
热议问题