Actually, the series ended with a three part episode called "Landmark." The building which housed the 12th precinct was sold to a private developer, and all of the detectives were reassigned to other precincts. Barney was promoted to Inspector.
And if you pay attention to the elevator in Castle you’ll see they’re in the 12th. That show is a festival of easter eggs.