DEV Community

Discussion on: Read-once variable - R1V, ROV, ... - in C#

Collapse
 
ankitbeniwal profile image
Ankit Beniwal

Hey Bruce,

Here is my variant:

public class R1V<Type>{
        private readonly Type _value;

        R1V(Type value){
            _value = value;
        }

        Type Get(){
            try{
                return _value;
            }
            finally{
                _value = null;
            }
        }
    }
Collapse
 
katnel20 profile image
Katie Nelson

Looks good except Type would have to be nullable.

Collapse
 
bugmagnet profile image
Bruce Axtens

I've created a dotnet core project and put that in it. Currently I'm getting a error in the finally clause: "A readonly field cannot be assigned to (except in a constructor or a variable initializer)".

Collapse
 
bugmagnet profile image
Bruce Axtens

Riiiight. Needed some publics.

using System;

namespace r1v
{
    class Program
    {
        static void Main(string[] args)
        {
            var r1v = new R1V<string>("Hello World");
            Console.WriteLine(r1v.Get());
            Console.WriteLine(r1v.Get());
        }
    }

    public class R1V<Type>{
        private Type _value;

        public R1V(Type value){
            _value = value;
        }

        public Type Get(){
            try{
                return _value;
            }
            finally{
                _value = default(Type);
            }
        }
    }
}
Collapse
 
bugmagnet profile image
Bruce Axtens • Edited

And then there's the property variant

using System;
using System.Diagnostics;

namespace r1v
{
    class Program
    {
        static void Main(string[] args)
        {
            var r1v = new R1V<string>("Hello World");
            Console.WriteLine(r1v.Get);
            Console.WriteLine(r1v.Get);
        }
    }

    public class R1V<Type>
    {
        private Type _value;

        public R1V(Type value) => _value = value;

        public Type Get
        {
            get
            {
                try
                {
                    return _value;
                }
                finally
                {
                    _value = default(Type);
                }
            }
        }
    }
}