Sunday, March 24, 2013

Useful Things to Know, #430: Casting to an Enum

We’re all familiar with defining an Enum.  In C#, they look like this:

public enum States
{
    Open,
    InUse,
    Closed
}

It’s understood by most people that Enum values are an alternate way of representing numeric constants.  Sometimes this is made explicit, as in the following:

public enum States
{
    Open = 1,
    InUse  = 2,
    Closed = 3
}

So when you assign to a value of type States, Intellisense will offer you a choice of three values:  States.Open, States.InUse, and States.Closed.

Are those the only values a variable of type States can have?

Actually, no. 

You can assign any integer to variable of an Enum, regardless of whether it’s defined as one of the available constants.  With the example above, the following:

States state = (States) 35;

… would be perfectly fine. Neither the compiler nor the runtime prevent this from happening.

So if your code looked like this:

if(state == States.Open)
{ 
   // do something
}
else if (state == States.InUse)
{
   // do something else
}
else {
   // assume the value must be States.Closed
}

… you have a potential bug. 

Labels:

Wednesday, March 13, 2013

Bad Idea Challenge #2

Consider the following database table:

CREATE TABLE Code
(
Code char(4) PRIMARY KEY
Description varchar(50)
)

It’s a brand new table in a database nobody is using but you.  You add it to an Entity Framework model and add a value to it, as in this test:

using(Model1DataContext dc = new Model1DataContext())
{
// Verify the table is empty:
Assert.AreEqual(0, dc.Codes.Count());

// Add and save a new record:
Code rcd = new Code() { Code = "X", Description = "A description" };
dc.Codes.Add(rcd);
dc.SaveChanges();

// That was one record. How many records do you think get returned?
Assert.AreEqual(1, dc.Codes.Count());
}

Surprise:  you’ll get 2 records back. 

Do you see why?

Hint:  if you inspect the two records, they’ll look superficially the same.  But there’ll be one key (ahem) difference. 

ETA:  No, the semantic key is not the Bad Idea.  But you’re close. 

Labels: