Nam Pham
Nam Pham

Reputation: 71

Assign value when calling method Syntax in C#

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
    }

Upvotes: 3

Views: 413

Answers (1)

Dai
Dai

Reputation: 155045

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

Upvotes: 3

Related Questions