Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting object to long

Tags:

c#

.net

casting

Unfortunately, in our (legacy) code base there is a property of a class that has type object and can be either a int or a long.

When trying to cast it to a long like this:

long id = (long) dBLockTabellenOptionen.Id;

I get the following exception:

Exception: Fehler in DoOneWorkRound:
Specified cast is not valid. Specified cast is not valid. -> Specified cast is not valid.
--- Exception Liste ---
System.InvalidCastException: Specified cast is not valid.

How can I savely cast it to a long without getting an exception?

Disclaimer: I know, that this property is a big smell but at this moment, the refactoring of it would be too much and since this application is going to get rewritten soon we will do it right then

like image 569
xeraphim Avatar asked Nov 05 '25 04:11

xeraphim


1 Answers

long id = Convert.ToInt64(dBlockTabellenOptionen.Id); should do the trick.

like image 60
user622505 Avatar answered Nov 08 '25 05:11

user622505



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!