Tvde1 Tvde1 - 3 days ago 4
C# Question

InvalidCastException in constructor when passing the right parameters

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

DataRow
:

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
Comment
is:

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


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

Exception Screenshot

Answer

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.

Edit:

Use this:

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