What’s an elegant way to refactor this code?
Say, I have the following object
public class SomeObject
{
public SomeInnerObject1 Cat { get; set; }
public SomeInnerObject2 Dog { get; set; }
public class SomeInnerObject1
{
public int Age { get; set; }
public string AgeAsString
{
get
{
if(Age < 0 )
throw new Exception();
return Age.ToString();
}
}
}
public class SomeInnerObject2
{
public string BirthDayString { get; set; }
public DateTime BirthDay { get { return DateTime.Parse(BirthDayString); } }
}
}
And say, I have to set a few textboxes’s values that I need to set
var obj = new SomeObject
{
Cat = new SomeObject.SomeInnerObject1 {Age = -1},
Dog = null
};
//These will pass but it looks ugly
try
{
textbox1.Text = obj.Dog.BirthDay.Month.ToString();
}
catch{ }
try
{
textbox2.Text = obj.Cat.AgeAsString;
}
catch { }
//These will fail
textbox1.Text = obj.Dog.BirthDay.Month.ToString();
textbox2.Text = obj.Cat.AgeAsString;
Is there a better way to do this?
Thanks,
Chi
When I really don’t care what happens for a particular line of code, I do something like this: