Get / Set as different types

I would like to define a variable that will take a string in SET, but then convert it to Int32 and use it during GET.

Here is the code I have:

private Int32 _currentPage; public String currentPage { get { return _currentPage; } set { _currentPage = (string.IsNullOrEmpty(value)) ? 1 : Convert.ToInt32(value); } } 
+6
c # properties
source share
4 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 parsing method might look like this:

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

This avoids formatting exceptions.

+10
source share

Keep in mind that this is a really really bad idea for the get and set property to be used for different types. Maybe a few methods will make more sense, and passing any other type will just hit this property.

 public object PropName { get{ return field; } set{ field = int.Parse(value); } 
+3
source share

What you have is the way it should be. There are no automatic conversions you are looking for.

0
source share

Using the magic blocks get and set, you have no choice but to take the same type that you return. In my opinion, the best way to handle this is to have the calling code do the conversion and just do the type Int.

0
source share

All Articles