Tvde1 Tvde1 - 4 months ago 15
C# Question

InvalidCastException in constructor when passing the right parameters

So I've got this method that creates an object fom a


public Comment CreateComment(DataRow row)
if (row == null) return null;
var id = (int) row["CommentPk"];
var song = (int) row["SongFk"];
var user = (int) row["AuthorFk"];
var text = (string) row["Content"];
var parent = (int?) row["ParentFk"];
return new Comment(_provider, id, song, user, text, parent);

And the constructor of

public Comment(Provider provider, int id, int songid, int userid, string content, int? parentId)

It does crash on the constructor line. I can step (
) to it:

Exception Screenshot

Answer Source

So it seems to be a problem with the nullable column ParentFk. Instead of

var parent = (int?) row["ParentFk"]

I used:

var parent = row["ParentFk"] == DBNull.Value ? null : (int?)row["ParentFk"];

I've used DataRows with nullable columns before but this weird exeption never happened, and it always became null.


Use this:

var parent = row.IsNull("ParentFk") ? null : (int?)row["ParentFk"]