In my little code snippet below I have a wrapper class for a simple dynamic object that, when not null, I can access two properties of, “id” and “name”. It’s a Facebook object, for those playing at home.
Anyway, in my GET accessor you can see I have to check if the dynamic object I was given was null, since referencing a dynamic property on a null reference will AV. But since I’m probably about the millionth person to do this, I assume there’s a more concise and elegant way to express this.
Please enlighten me, oh mighty sages. Thanks!
public class IdNamePair
{
private dynamic _data;
public IdNamePair(dynamic data)
{
_data = data;
}
public string Id
{
get
{
return (_data == null) ? null : _data.id;
}
}
public string Name
{
get
{
return (_data == null) ? null :_data.name;
}
}
}
There is nothing wrong with what you have done, the only thing I would do is drop the brackets and change the evaluation:
Doing it that way is just (IMVHO) slightly easier to read, but fundamentally identical to what you had.