jaleel
jaleel

Reputation: 391

c# assign conditional value to class member

is there any way to assign conditional value to a class member within same class?

public class getStudent
{
private bool itsOkay = false;
private short stID = 0;

public bool ValusOkay
    {
        get  {return itsOkay;}
        set  {itsOkay = value;}
    }
 public short STid
    {
        get {return stID;}
        if(itsOkay == true)
           set {stID = 8;}
        else
           set {stID = 0;}
    }    
}

Thank you in advance.

Upvotes: 0

Views: 1797

Answers (3)

ssilas777
ssilas777

Reputation: 9764

You can try this

Also to cast from int to short in ternary operator, the syntax should be like this

    public short STid
    {
        get {return stID;}

        set {stID = itsOkay  ? (short)8 : (short) 0;}          
    } 

Upvotes: 3

Benji Wa
Benji Wa

Reputation: 137

If your code actually shows what you are trying to you don't need a setter at all.

public short STid => (itsOkay) ? (short) 8 : (short) 0;

This will create a getter returning 8 or 0 depending on the given condition.

Upvotes: 0

Roman
Roman

Reputation: 12201

You can put anything inside get or set method - if, for, while ....., but its not recommended to put a lot of lines of code in property. But in your case you can simply put your if inside setter:

public short STid
{
    get {return stID;}
    set 
    {
        if(itsOkay == true)
            stID = 8;        
        else
            stID = 0;
    }
}

Upvotes: 1

Related Questions