Spread Operator Like JS, to Create Different Objects (Especially Extended Objects) Easily #6971
-
Hi, in JS language we have a spread operator, so that we can create an object from another, it takes all properties from the other class. let elements = [{"n":1},{"n":5}]
let y = elements.map((item,i)=>{...item, "description":"current: "+i}) I could easily create another object. public class Base{
public string Name {get;set;}
public string ID {get;set;}
// a bunch of lots of other attributes
}
public class Extended: Base{
public string Description {get;set;}
} I just want to create an extended class instance from a base class instance. I can copy every attribute, I can loop through all attributes but this is so boring. Can we create something for this? Like for example this: var baseList = new List<Base>();
baseList.Add(new Base(){ID="1",Name="name"})
//baseList.Add....
var extendedList = baseList.Select(base=>new Extended(){...base, Description="it's extended"}).ToList() |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
I believe there are downsides to this: this is property based like get/set or get/init so there is no way to guarantee correctness of object creation. Constructors are hard to link with this feature. Private fields too. What if derived class declares a "new" member with same name but it's get-only? Maybe if you narrow it down to records only it can work? Not sure Also when you think about ts/js spread then obviously structural spread comes to mind. Like why would you tie yourself to inheritance with this feature? Seems limited. |
Beta Was this translation helpful? Give feedback.
-
Here is the problem I have: https://stackoverflow.com/questions/14613919/copying-the-contents-of-a-base-class-from-a-derived-class |
Beta Was this translation helpful? Give feedback.
-
This is a duplicate of #2879. |
Beta Was this translation helpful? Give feedback.
This is a duplicate of #2879.