Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ensure Variable Initialization C#

Consider this code:

public string Variable1 { get; set;}
public int Variable2 { get; set;}

public void Function()
{
 // Has been Variable1 Initialized?
}

Inside the function, I want to know if a value has been sent to Variable1 & Variable2, prior to the function call,

even if the DEFAULT values have been sent, that's ok (null for string & 0 for int)

like image 352
Cătălin Rădoi Avatar asked May 20 '15 08:05

Cătălin Rădoi


1 Answers

Consider using a simple wrapper like this:

public struct AssignableProperty<T>
{
    private T _value;

    public T Value
    {
        get { return _value; }
        set
        {
            WasAssigned = true;
            _value = value;
        }
    }

    public bool WasAssigned { get; private set; }

    public static implicit operator AssignableProperty<T>(T data)
    {
        return new AssignableProperty<T>() { Value = data };
    }

    public static bool operator ==(AssignableProperty<T> initial, T data)
    {
        return initial.Value.Equals(data);
    }

    public static bool operator !=(AssignableProperty<T> initial, T data)
    {
        return !initial.Value.Equals(data);
    }

    public override string ToString()
    {
        return Value.ToString();
    }
}

Then your class'll look like this:

public class Test
{
    public AssignableProperty<string> Variable1 { get; set; }
    public AssignableProperty<int> Variable2 { get; set; }

    public void Function()
    {
        if(Variable1.WasAssigned&&Variable2.WasAssigned)
            //do stuff
    }
}

You can go further and add throw Exception or contract to getter, so if somebody'll try to access uninitialized value it'll throw an exception or show you warning

like image 140
Alex Voskresenskiy Avatar answered Sep 29 '22 13:09

Alex Voskresenskiy