Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign value when calling method Syntax in C#

Tags:

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
    }
like image 470
Nam Pham Avatar asked May 07 '26 10:05

Nam Pham


1 Answers

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

like image 108
Dai Avatar answered May 10 '26 02:05

Dai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!