Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

569
Vistas
Is it possible to create a C# record with a private constructor?

Hello,

I´m trying to rebuild a discriminated union type in C#.
I always created them with classes like this:

public abstract class Result
{
    private Result() { }

    public sealed class Ok : Result
    {
        public Ok(object result)    // don´t worry about object - it´s a sample
            => Result = result;
        
        public object Result { get; }
    }

    public sealed class Error : Result
    {
        public Error(string message)
            => Message = message;

        public string Message { get; }
    }
}

The problem is that is sooooo much boilerplate code when comparing to F#:

type Result =
    | Ok of result : object
    | Error of message : string

So I tried to rebuild the type with the help of C#9 records.

public abstract record Result
{
    public sealed record Ok(object result) : Result;
    public sealed record Error(string message) : Result;
}

Now it is way less code but now there is the problem that anyone make new implementations of Result because the record has a public constructor.

Dose anyone have an idea how to restrict the implementations of the root record type?

Thanks for your help and your ideas! 😀 💡

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

I solved it with the help of your comments and this other stackoverflow article.

namespace System.Runtime.CompilerServices
{
    internal static class IsExternalInit { }
}

namespace RZL.Core.Abstractions.DMS
{
    public abstract record Result
    {
        private Result() { }

        public sealed record Ok(object result) : Result;
        public sealed record Error(string message) : Result;
    }
}
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda