DEV Community

Simon Foster
Simon Foster

Posted on • Originally published at funkysi1701.com on

Casting and Converting between types

Recently I was asked how to convert a number to a string. Let’s look at a few ways of approaching this problem.

Most objects in c# have a method called ToString() which displays the string representation of that object. This is because of inheritance, all objects inherit from System.Object which defines ToString().

Int32 is a struct so it inherits from System.ValueType which also inherits from System.Object

so in code

int a = 9;

string b = a.ToString();

Now let’s look at the reverse. However the reverse runs the risk of throwing an error, let’s look at why.

string b= “9”;

string c =”a”;

string d = “two”;

All are valid strings but only one can be converted to a number. Use the TryParse method to convert to a number.

int.TryParse(“9”, out int e);

TryParse will not throw an exception if the conversion fails, if it succeeds variable e will contain the result. Note an earlier version of c# required you to define the out parameter before using it with TryParse.

int.Parse exists to do the same thing however it will throw exceptions if a conversion is not possible. The same is true if you use Convert.ToInt32(“two”);

Casting

Casting is a way to explicitly telling the compiler that a type is actually another type and you are aware data loss will occur.

double x = 4.5;

int y = (int)x;

However it is not possible to cast a string to a number format as a string can contain any character not just number characters.

The post Casting and Converting between types appeared first on Funky Si's Tech Talk.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay