1
Hello, I have a question regarding C# and the optimization of the form of code generation. In Typescript, if I have the code below I can create a new object from a previous one and, in the creation itself of that object I can add to the same new properties, like this:
class Foo {
Bar: string;
Bin: number;
}
const foo = new Foo();
foo.Bar = 'teste';
const foo2 = {...foo, Bin: 123};
in C# I am obliged to define the foo2 defining property in property, which (in my view) reduces the declaration speed in the code, thus:
public class Foo {
public string Bar { get; set; }
public int Bin { get; set; }
}
public class Program {
public static void Main(string[] args)
{
var foo = new Foo() {
Bar = "teste"
};
var foo2 = new Foo() {
Bar = foo.Bar,
Bin = 123
};
}
}
In this example I have only 1 property, so it is not so bad to replicate the statement, but if I have a class with many properties, it is already costly and tiring...
Is there any way that I can infer from the initialization of an object that it will have the properties of another of the same type and also have new properties? What you’re looking for would be something like this:
// ... código aqui...
var foo2 = new Foo(){ ...foo, Bin = 123 };
I don’t understand, because there’s even a way to cross a
array
C# with the word reservedparams
, but, your example is not based on that, could edit and put a better example?– novic