DEV Community

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

Collapse
 
bugmagnet profile image
Bruce Axtens • Edited

Thanks to everyone who contributed.

As I was fiddling with this, I thought, "hey why not just"

        public T Value
        {
            get
            {
                var _returning = _value;
                _value = default(T);
                return _returning;
            }
        }

Well, that's fine until you do this

            var r1vc = new R1V<Klasse>(new Klasse() { klasse = "Hello, Class" });
            Console.WriteLine(r1vc.Value.klasse);
            Console.WriteLine(r1vc.Value.klasse);

after having defined the class Klasse as

    public class Klasse
    {
        public string klasse { get; set; }
    }

The first WriteLine gives "Hello, Class" but the second one throw an error, namely {"Object reference not set to an instance of an object."} when evaluating var _returning = _value; so one must have atry{}finally{} in the property declaration.

LATER

In fact, even

            try{
                return _value;
            }
            finally{
                _value = null;
            }

doesn't cut it in the Klasse version.

LATER AGAIN

Actually, it does cut it. So perhaps the first one is okay too. The problem is in the second Console.WriteLine(r1vc.Value.klasse); because the second r1vc.Value returns null. So getting klasse of null is an error. Soooooo ... I need to do something like

            Console.WriteLine(r1vc.Value == null ? "" : r1vc.Value.klasse);
Collapse
 
ankitbeniwal profile image
Ankit Beniwal

Implemented this program in java.. That's why i didn't faced those issues except the return value null conversion error.

Glad you solved it. Cheers 🥂