3

I am sorry I don't know if C# has this syntax or not and I don't know the syntax name. My code below, I want to add 2 people has the same name but not age. So I am wondering if C# has a brief syntax that I can change the Age property value when calling AddPerson method. Please tell me if I can do that? If can, how can I do? Thank you.

class Program
    {
        static void Main(string[] args)
        {
            //I want to do this
            Person p = new Person
            {
                Name = "Name1",
                //And other propeties
            };
            AddPerson(p{ Age = 20}); 
            AddPerson(p{ Age = 25}); //Just change Age; same Name and others properties

            //Not like this(I am doing)
            p.Age = 20;
            AddPerson(p);
            p.Age = 25;
            AddPerson(p);

            //Or not like this
            AddPerson(new Person() { Name = "Name1", Age = 20 });
            AddPerson(new Person() { Name = "Name1", Age = 25 });
        }
        static void AddPerson(Person p)
        {
            //Add person
        }
    }
    class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
        //And more
    }
2
  • Do you mean Person1.Age = Person2.Age because this will assign the Age of Person2 to Age of PErson1 Commented Dec 17, 2020 at 1:04
  • Since Person is a class, if you wish to have multiple instances in memory with different values, you must create those separate instances somewhere. Commented Dec 17, 2020 at 1:06

1 Answer 1

3

If Person is a Record-Type, then yes: by using C# 9.0's new with operator. Note that this requires C# 9.0, also note that Record-Types are immutable.

public record Person( String Name, Int32 Age );

public static void Main()
{
    Person p = new Person( "Name1", 20 );
    
    List<Person> people = new List<Person>();

    people.Add( p with { Age = 25 } );
    people.Add( p with { Age = 30 } );
    people.Add( p with { Name = "Name2" } );
}

This is what I see in LinqPad when I run it:

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

This way is really brief and this is what I want. But I is bad luck it requires C# 9.0 so I can't use for my current program because my project is now in lower version of C#. I will remember this and apply for next project. Thank you very much.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.