Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getters Setters

I am confused to no end.

The code that seems to have to work the same – works different.
An explanation would be nice.

The following code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public int Pages
{
    get { return _pages; }
    set
    {
        if (value < 1)
        {
            _pages = 1;
        }
        else { }
        _pages = value;
    }
}

In case i set page value to 0 or a negative value – the value is set to 1.
Works just fine.

It also works just fine in the following example:

public int Pages
{
    get { return _pages; }
    set
    {
        if (value < 1)
        {
            _pages = 1;
        }
        else 
        {
            _pages = value; 
        }
        
    }
}

However.

 public string Title
 {
     get { return _title; }
     set
     {
         if (value == "")
         {
             _title = "Default";
         }
         else
         {
             
         }
         _title = value;
     }
 }

This block of code, which essentially should do the exact same thing, except it checks if the string is empty, and sets the string value to "Default" – fails to do so.
Whenever the string value is empty – it remains empty.

Now if i move the _title = value; into the body of the else statement – it works fine.

Working code example:

public string Title
{
    get { return _title; }
    set
    {
        if (value == "")
        {
            _title = "Default";
        }
        else
        {
            _title = value;
        }
        
    }
}

Why is that so?
How come the same code with different data type gives different outcome?
What is the part i am missing here?

If you are kind enough to explain – thanks a lot.

>Solution :

The code is correct… in:

if (value == "")
         {
             _title = "Default";
         }
         else
         {
             
         }
         _title = value;

_title always will be value.. because if set "" it set twice:

_title = "Default"
AND
_title = value ("")

then always will be VALUE

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading