Unassigned local variable

The last day I saw a C# programming problem at StackOverflow. The problem is actually a compilation error from C# compiler. The error is ‘Unassigned local variable’.

 The problem

‘this is probably quite a simple problem, however, I can’t figure out how to get around this. Basically, my class Client requires a work address value, however, it’s not 100% required when creating a client. In creating the variable to be used for the object creation i’m using a string value which will then get the value from a text box. I am then checking to see if the textbox is empty, if it is, the string value of the variable is just a whitespace. Else, it’s the textbox value.


string homeAdd;
if(homeAddressText.Text  ==  String.Empty)
{
    homeAdd = " ";
}
else if (homeAddressText.Text  !=  String.Empty)
{
    homeAdd = homeAddressText.Text;
}

As seen here..

However, when I go to create the client object using this variable, I get an error saying ‘use of unassigned local variable ‘homeAdd’.

Client client = new Client(firstN, lastN, homeAdd, workAdd, email, homeP, cellP);

Is there a simple way I can do the checking I require and still use the variable?
Thanks in advance guys/gals.’

This was the problem posted in StackOverflow.

The solution
Actually C# does not allow unassigned local variables. You have to assign local variables before use. In this case if this guy changes the else if to only else then the program compiles successfully. First if then else if. Compiler is not sure that this two if conditions satisfy every time or not. If not then the homeAdd local variable is become unassigned. But if he changes the else if to else, then compiler become sure that among if and else at least one must be executes in every time, that means homeAdd local variable gets assigned.


string homeAdd;
if(homeAddressText.Text  ==  String.Empty)
{
    homeAdd = " ";
}
else
{
    homeAdd = homeAddressText.Text;
}

The other solution is assign the homeAdd local variable with some default value.


string homeAdd = String.Empty;
if(homeAddressText.Text  ==  String.Empty)
{
    homeAdd = " ";
}
else if (homeAddressText.Text  !=  String.Empty)
{
    homeAdd = homeAddressText.Text;
}

The software design
I have created a demo code to show you how this problem can be solve if I was in the same setuation.

internal class Client
{
    // Class fields and properties.
    private string firstName;
    public string FirstName
    {
        get { return firstName; }
        set { SetStringValue(ref firstName, value); }
    }

    private string lastName;
    public string LastName
    {
        get { return lastName; }
        set { SetStringValue(ref lastName, value); }
    }

    private string homeAddress;
    public string HomeAddress
    {
        get { return homeAddress; }
        set
        {
            if (!string.IsNullOrEmpty(value))
            {
                homeAddress = value;
            }
            else
            {
                homeAddress = "No home address";
            }
        }
    }

    private string workAddress;
    public string WorkAddress
    {
        get { return workAddress; }
        set { SetStringValue(ref workAddress, value); }
    }

    private string email;
    public string Email
    {
        get { return email; }
        set { SetStringValue(ref email, value); }
    }

    private long homePhone;
    public long HomePhone
    {
        get { return homePhone; }
        set { SetLongValue(ref homePhone, value); }
    }

    private long cellPhone;
    public long CellPhone
    {
        get { return cellPhone; }
        set { SetLongValue(ref cellPhone, value); }
    }

    // Constructors.
    public Client(string firstName, string lastName, string homeAddress,   string workAddress, string email, long homePhone, long cellPhone)
    {
        this.FirstName = firstName;
        this.LastName = lastName;
        this.HomeAddress = homeAddress;
        this.WorkAddress = workAddress;
        this.Email = email;
        this.HomePhone = homePhone;
        this.CellPhone = cellPhone;
    }

    // Supporting methods for initialization.
    private void SetStringValue(ref string field, string value)
    {
        if (!string.IsNullOrEmpty(value))
        {
            field = value;
        }
        else
        {
            throw new NullReferenceException();
        }
    }

    private void SetLongValue(ref long field, long value)
    {
        if (value != 0)
        {
            field = value;
        }
        else
        {
            throw new NotSupportedException();
        }
    }
}

First I have created a Client class. This Client class has some properties, like first name, last name, home address, work address, email, home phone and cell phone. All the properties except home and cell phone are string data type. Home and cell phone has long data type. I have also created two supporting (private) methods in Client class. These two methods are doing the required field validation work in the set accesser of the properties.

SetStringValue() method is doing the required field validation for string properties.

private string firstName;
public string FirstName
{
    get { return firstName; }
    set { SetStringValue(ref firstName, value); }
}

private void SetStringValue(ref string field, string value)
{
    if (!string.IsNullOrEmpty(value))
    {
        field = value;
    }
    else
    {
        throw new NullReferenceException();
    }
}

SetLongValue() method is doing the required field validation for long properties.

private long homePhone;
public long HomePhone
{
    get { return homePhone; }
    set { SetLongValue(ref homePhone, value); }
}

private void SetLongValue(ref long field, long value)
{
    if (value != 0)
    {
        field = value;
    }
    else
    {
        throw new NotSupportedException();
    }
}

Home address has no required field validation in their set accessor.

Also I have created a ClientDemo class to test Client class.

internal class ClientDemo
{
    static void Main(string[] args)
    {
        // Inputs.
        Console.Write("Enter your first name: ");
        string firstName = Console.ReadLine();

        Console.Write("Enter your last name: ");
        string lastName = Console.ReadLine();

        Console.Write("Enter your home address: ");
        string homeAddress = Console.ReadLine();

        Console.Write("Enter your work address: ");
        string workAddress = Console.ReadLine();

        Console.Write("Enter your email: ");
        string email = Console.ReadLine();

        Console.Write("Enter your home phone: ");
        long homePhone = long.Parse(Console.ReadLine());

        Console.Write("Enter your cell phone: ");
        long cellPhone = long.Parse(Console.ReadLine());

        // Create client object, assuming that without home address all the fields have data.
        Client myClient = null;
        try
        {
            myClient = new Client(firstName, lastName,homeAddress,workAddress, email, homePhone, cellPhone);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

        // Show result.
        Console.WriteLine();

        if (myClient != null)
        {
            Console.WriteLine(myClient.FirstName);
            Console.WriteLine(myClient.LastName);
            Console.WriteLine(myClient.HomeAddress);
            Console.WriteLine(myClient.WorkAddress);
            Console.WriteLine(myClient.Email);
            Console.WriteLine(myClient.HomePhone);
            Console.WriteLine(myClient.CellPhone);
        }
    }
}

Full code

using System;

internal class Client
{
    // Class fields and properties.
    private string firstName;
    public string FirstName
    {
        get { return firstName; }
        set { SetStringValue(ref firstName, value); }
    }

    private string lastName;
    public string LastName
    {
        get { return lastName; }
        set { SetStringValue(ref lastName, value); }
    }

    private string homeAddress;
    public string HomeAddress
    {
        get { return homeAddress; }
        set
        {
            if (!string.IsNullOrEmpty(value))
            {
                homeAddress = value;
            }
            else
            {
                homeAddress = "No home address";
            }
        }
    }

    private string workAddress;
    public string WorkAddress
    {
        get { return workAddress; }
        set { SetStringValue(ref workAddress, value); }
    }

    private string email;
    public string Email
    {
        get { return email; }
        set { SetStringValue(ref email, value); }
    }

    private long homePhone;
    public long HomePhone
    {
        get { return homePhone; }
        set { SetLongValue(ref homePhone, value); }
    }

    private long cellPhone;
    public long CellPhone
    {
        get { return cellPhone; }
        set { SetLongValue(ref cellPhone, value); }
    }

    // Constructors.
    public Client(string firstName, string lastName, string homeAddress,   string workAddress, string email, long homePhone, long cellPhone)
    {
        this.FirstName = firstName;
        this.LastName = lastName;
        this.HomeAddress = homeAddress;
        this.WorkAddress = workAddress;
        this.Email = email;
        this.HomePhone = homePhone;
        this.CellPhone = cellPhone;
    }

    // Supporting methods for initialization.
    private void SetStringValue(ref string field, string value)
    {
        if (!string.IsNullOrEmpty(value))
        {
            field = value;
        }
        else
        {
            throw new NullReferenceException();
        }
    }

    private void SetLongValue(ref long field, long value)
    {
        if (value != 0)
        {
            field = value;
        }
        else
        {
            throw new NotSupportedException();
        }
    }
}

internal class ClientDemo
{
    static void Main(string[] args)
    {
        // Inputs.
        Console.Write("Enter your first name: ");
        string firstName = Console.ReadLine();

        Console.Write("Enter your last name: ");
        string lastName = Console.ReadLine();

        Console.Write("Enter your home address: ");
        string homeAddress = Console.ReadLine();

        Console.Write("Enter your work address: ");
        string workAddress = Console.ReadLine();

        Console.Write("Enter your email: ");
        string email = Console.ReadLine();

        Console.Write("Enter your home phone: ");
        long homePhone = long.Parse(Console.ReadLine());

        Console.Write("Enter your cell phone: ");
        long cellPhone = long.Parse(Console.ReadLine());

        // Create client object, assuming that without home address all the fields have data.
        Client myClient = null;
        try
        {
            myClient = new Client(firstName, lastName,homeAddress,workAddress, email, homePhone, cellPhone);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

        // Show result.
        Console.WriteLine();

        if (myClient != null)
        {
            Console.WriteLine(myClient.FirstName);
            Console.WriteLine(myClient.LastName);
            Console.WriteLine(myClient.HomeAddress);
            Console.WriteLine(myClient.WorkAddress);
            Console.WriteLine(myClient.Email);
            Console.WriteLine(myClient.HomePhone);
            Console.WriteLine(myClient.CellPhone);
        }
    }
}

If you have any better design, please send me code samples.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s