views:

40

answers:

2

In my code behind, I grab a value from the selected index from a radiobuttonlist.

Question is, in some cases I need to use it as a string but other cases I need to convert it to Int32 for use in some methods.

Is it better to:

Convert to int using a property (possible reuse later on) Convert to int inside just one method that needs it at this moment

I figure a private property will allow reuse across multiple methods internally. But if only one method really needs it to be an integer and that method uses it in a couple calls by passing it as a string parameter inside that method, just do the conversion there in that method and forget about exposing it as a private property with the assumption that someone may want to use it in some other method in this code behind later.

+1  A: 

I would think of this as model view controller. The view sees this value as a String but the actual type of the value in the model is an integer. Therefore you should store it as an integer and then convert it to a String view as needed by the model clients.

Peter Kelley
let me explain better. I am grabbing the selected index value from the radiobuttonlist as so in my code-behind: _someID = rblMyRadiobuttonList.SelectedValue; where _someID is a string because SelectedValue returns the value behind the SelectedText.
So I need to use the selectedvalue both as a string and integer in various methods in my class. I thought to expose the conversion to integer as a property for reuse internally now and later on.
note that _someID is a private string field in my code-behind, that is set inside a click event
By "model" I didn't necessarily mean the database, I meant your model layer in your code. The principle still applies, store the value in its canonical format as an integer and then let those methods that need it as a String do their own conversion.
Peter Kelley
A: 

It is better to convert to int [and expose it as] a property

In general, I would present the value as the most specific type I can put it in.

If the value always has an integer representation, then just present it as an integer property. If someone needs to use it as a string, they can call .ToString() themselves to convert it back.

private void UpdateValue()
{
   _selectedValue = Int32.Parse(GetSelectedValue());
}

private int _selectedValue;

public int SelectedValue
{
   get { return _selectedValue; }
}

In many cases, whoever is using your code won't even need to call .ToString(), for example:

string description = string.Format("Selected Value: {0}", obj.SelectedValue);
Daniel LeCheminant