Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

121
Visualizações
Record type with multiple constructors

How do I create multiple constructors for a record type in C#?

I created a record type like this:

public record Person(int Id, string FirstName, string LastName)

Now I want to introduce another constructor overload with no parameters, how can I do that? In a normal class I would do something like this:

public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public Person()
    {
        
    }

    public Person(int id, string firstName, string lastName)
    {
        Id = id;
        FirstName = firstName;
        LastName = lastName;
    }
}
over 4 years ago · Santiago Trujillo
4 Respostas
Responde à pergunta

0

Use optional arguments.

public record Person(int Id = default, string FirstName = null, string LastName = null);
over 4 years ago · Santiago Trujillo Relatório

0

You can write your code like below:

public record Person
{
    public int Id { get; init; }
    public string FirstName { get; init; }
    public string LastName { get; init; }
    //constructor
    public Person()
    {
        //init or do something
    }
    //overload constructor
    public Person(int id, string firstName, string lastName)
    {
        Id = id;
        FirstName = firstName;
        LastName = lastName;
    }
}
over 4 years ago · Santiago Trujillo Relatório

0

The selected answer works for this simple case where all the members are simple types. With reference types you usually want to call their constructors etc.

The right solution is to simply add the constructor you want like this:

public Rank(int level, string description);

record Manager(string FirstName, Rank rank) {
  public Manager() : this("", new(0, "Entry") { }
}
over 4 years ago · Santiago Trujillo Relatório

0

you can write it like this:

Public record Person(int Id,string FirstName,string LastName){
   Public Person(YourDto item):this(item.Id,item.FirstName,item.LastName){} 
}

so, in the constructor you can pass your Dto item.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda