Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get/Set as different types

I'd like to define a variable that will accept a string in the SET, but will then convert it to an Int32 and use that during the GET.

Here the code that I currently have:

private Int32 _currentPage;

public String currentPage
{
   get { return _currentPage; }
   set 
   {
      _currentPage = (string.IsNullOrEmpty(value)) ? 1 : Convert.ToInt32(value);
   }
}
like image 680
Damiro Avatar asked Mar 22 '11 19:03

Damiro


2 Answers

I would suggest an explicit Set method:

private int _currentPage;

public int CurrentPage
{
    get
    {
        return _currentPage;
    }
}

public void SetCurrentPage(string value)
{
        _currentPage = (string.IsNullOrEmpty(value)) ? 1 : Convert.ToInt32(value);
}

As a side note, your parse method may do better like this:

if (!int.TryParse(value, out _currentPage)
{
    _currentPage = 1;
}

This avoids the formatting exceptions.

like image 149
John Gietzen Avatar answered Sep 29 '22 12:09

John Gietzen


Be aware that this is really really bad idea to have a property get & set being used against different types. May be couple of methods would make more sense, and passing any other type would just blow up this property.

public object PropName
{
    get{ return field; }
    set{ field = int.Parse(value);            
}
like image 39
Sanjeevakumar Hiremath Avatar answered Sep 29 '22 11:09

Sanjeevakumar Hiremath