Why am i encountering 'invalidcastexception in c#'?

Example:

object obj = "Hello";
int num = (int)obj;
Solution:

This error is raised when you try to cast an object to a type it doesn't belong to. Ensure proper type checking before casting.


if(obj is int) {
    int num = (int)obj;
}

Beginner's Guide to C#