0

If _model.SubBrand is a string, is there a more elegant way to convert it to a nullable int? What I'm doing right now feels clunky:

public int? SubBrandIndex
{
    get
    {
        return _model.SubBrand == null ?
            (int?)null : Convert.ToInt32(_model.SubBrand);
    }
}
Riegardt Steyn
  • 5,431
  • 2
  • 34
  • 49
  • 3
    [Convert string to nullable type (int, double, etc...)](http://stackoverflow.com/questions/773078/convert-string-to-nullable-type-int-double-etc) – Ulugbek Umirov Apr 11 '14 at 12:02

2 Answers2

2

In order to avoid exceptions, you should also check invalid strings

public int? SubBrandIndex
{
    get
    {
        int value;
        return int.TryParse(subBrand, out value) ? (int?)value : null;
    }
}
CuriousPen
  • 249
  • 1
  • 8
  • Maybe `_model.SubBrand` is not assigned from the user and if a non-null string cannot be parsed it should be treated as exception since it's a bug. If you return a nullable-int you cannot differentiate between a null-string and an invalid non-null string. – Tim Schmelter Apr 11 '14 at 12:21
1

Why do you want one-liners, in my opinion this is very clear and readable:

public int? SubBrandIndex
{
    get
    {
        int? subBrandIndex = null;
        if (_model.SubBrand != null)
            subBrandIndex = int.Parse(_model.SubBrand);
        return subBrandIndex;
    }
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939