Actor had served two years of a three to 10-year prison sentence
The Pennsylvania Supreme Court ruled that Mr Cosby should never have been charged in the case, after reaching an agreement with a previous prosecutor.
Mr Cosby, 83, had always denied any guilt and said he would rather serve the maximum sentence of 10 years than express remorse for the alleged 2004 incident with his accuser Andrea Constand.
The Temple University employee accused The Cosby Show actor of inviting her to his Pennsylvania estate for career advice, where she claims he drugged and sexually assaulted her.
Mr Cosby was arrested and charged in 2015, just days before the state’s 12-year statute of limitations was set to expire.
The court has now ruled that Montgomery County District Attorney Kevin Steele was obligated to keep to an agreement made by his predecessor Bruce Castor to not charge Mr Cosby when he later gave potentially incriminating testimony in a deposition as part of Ms Constand’s civil lawsuit.
Justice David Wecht, writing for a split court, said Mr Cosby had relied on the previous prosecutor’s decision not to charge him when he gave his deposition.
The judge added that overturning Mr Cosby’s prosecution was “the only remedy that comports with society’s reasonable expectations of its elected prosecutors and our criminal justice system”.
During Mr Cosby’s first trial, which ended in a hung jury, the trial judge only allowed one other accuser to testify against him.
But during the retrial the judge allowed five other accusers to testify about incidents with Mr Cosby during the 1980s.
The state Supreme Court ruled that the testimony tainted the trial, even though a lower court had found it appropriate,
The court says that Mr Cosby cannot be retried on the same charges.
“When an unconditional charging decision is made publicly and with the intent to induce action and reliance by the defendant, and when the defendant does so to his detriment (and in some instances upon the advice of counsel), denying the defendant the benefit of that decision is an affront to fundamental fairness, particularly when it results in a criminal prosecution that was foregone for more than a decade,” the high court ruled. “For these reasons, Cosby’s convictions and judgment of sentence are vacated, and he is discharged.”
Mr Cosby, who has made an estimated $400m during his career, could be free from prison later on Wednesday.
Pennsylvania has been one of the 15 states that do not pay inmates any money for wrongful convictions, which in other states can be as much as $50,000 per year of incarceration.
But in February Governor Tom Wolf included a proposal to pay the same figure in his 2021-2022 budget plan.
The Associated Press contributed to this report.