简体   繁体   中英

Filtering my property in a getter

Here is my code:

private Analyst _PrimaryAnalyst;
public Analyst PrimaryAnalyst
{             
    get       
    {
        Analyst activeAnalysts;

        if (this.PrimaryAnalyst.IsActive == true)
        { 
            activeAnalysts = _PrimaryAnalyst;
        }

        return activeAnalysts; //"Use of unassigned local variable"               
    }         
    set
    {              
        SetPropertyValue("PrimaryAnalyst", ref _PrimaryAnalyst, value);                          
    }
}

Basically I am trying to filter my Analyst property based on if they are marked Active or not. Then I want to to return only Active Analysts. (Based on a bool property of Analyst), I am getting an error on the return statement saying "Use of unassigned local variable"

However I am clearly assigning it in the if statement?

Change the first line of the getter to:

Analyst activeAnalysts = null;

The issue is that if the if statement evaluates to false, then the value is never set, so the compiler doesn't know what it should return.

The reason you're getting the error is that not all code paths lead to an assignment. You should either initialize the variable before the if , or include an else and assign it to something there.

Also, you should be checking your private variable in the if statement instead of the public one (to avoid a StackOverflowException ), and, assuming that Analyst is a nullable class, you should also ensure it's not null before checking IsActive . A property getter should not throw an exception.

Your getter can be also be simplified using a ternary assignment:

get
{
    return (_PrimaryAnalyst != null && _PrimaryAnalyst.IsActive) 
        ? _PrimaryAnalyst 
        : null;
} 

In C# you can not use a local variable before assigning it a value.

C# Language Specification, section 1.6.6.2

C# requires a local variable to be definitely assigned before its value can be obtained

lets get to your code

what happen if this.PrimaryAnalyst.IsActive is false? Yes, Use of unassigned local variable

you can fix this by initializing the local variable.

Analyst activeAnalysts = null;

or

if (this.PrimaryAnalyst.IsActive == true)
{ 
    activeAnalysts = _PrimaryAnalyst;
}
else
{
     activeAnalysts = null;
}

but there is another problem here. Your code leads to StackOverflowException because you are calling a method inside itself (recursion) but there is no way out of it so it leads to StackOverflow Exception you should change the line this.PrimaryAnalyst.IsActive == true to _PrimaryAnalyst.IsActive == true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM