public bool HaveIBeenSet
{
get { return _somePrivateMember != null; }
}
This worked just fine when it was an object. But in my refactoring, I changed it to a generic KeyValuePair
And then my mind went blank. How do you check to see whether a generic struct has been initialized or not? I don't think I've ever had to answer that question before. It kind of blew my mind.
One of my coworkers pointed me in the direction of the default keyword. Quoting MSDN:
"For structs, it will return each member of the struct initialized to zero or null depending on whether they are value or reference types."
public bool HaveIBeenSet
{
get { return _somePrivateMember != default(KeyValuePair
}
Still fails, claiming that "Operator '!=' cannot be applied to operands of type KeyValuePair
But I can get around this with:
public bool HaveIBeenSet
{
get { return _somePrivateMember.Key != default(KeyValuePair
}
I could be really thorough and compare values as well, but this is sufficient for my needs.
You learn something new every day.
See the default keyword at MSDN here.
1 comments:
The following did not work for me:
default(KeyValuePair).Key
I found that I had to insert the generic types in brackets after the "KeyValuePair". In my case it was a pair of ints.
Good info nonetheless!
Post a Comment