Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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! 😀 💡

like image 688
JakobFerdinand Avatar asked Sep 22 '21 12:09

JakobFerdinand


People also ask

How is C created?

The origin of C is closely tied to the development of the Unix operating system, originally implemented in assembly language on a PDP-7 by Dennis Ritchie and Ken Thompson, incorporating several ideas from colleagues. Eventually, they decided to port the operating system to a PDP-11.

Does a C+ exist?

C+ (grade), an academic grade. C++, a programming language. C with Classes, predecessor to the C++ programming language.

Is C very difficult?

C is more difficult to learn than JavaScript, but it's a valuable skill to have because most programming languages are actually implemented in C. This is because C is a “machine-level” language. So learning it will teach you how a computer works and will actually make learning new languages in the future easier.

Can you make an AI with C?

In short, YES! Its possible. Any language can be used to implement AI.


1 Answers

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;
    }
}
like image 151
JakobFerdinand Avatar answered Sep 28 '22 12:09

JakobFerdinand