Tuesday, November 11, 2008

The 'default' Keyword

I was refactoring some code today and I came across a condition where I'm checking to see if a value had been set via a null check:

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, which is a struct.

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 and KeyValuePair" (the same type in both cases).

But I can get around this with:

public bool HaveIBeenSet
{
get { return _somePrivateMember.Key != default(KeyValuePair).Key}
}


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:

Anonymous said...

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!