Casting VS Converting VS Parsing in C#: Which to choose?

Описание к видео Casting VS Converting VS Parsing in C#: Which to choose?

In this video we will discuss the difference between converting, parsing, and casting in C#
Become a PRO developer: https://bit.ly/3mKYW4X

Welcome back to a new C# tutorial, in this tutorial we will discuss the difference between converting, parsing, and casting in C#.

This might be a confusing topic since not a lot of developers know the exact difference between the 3 methods, also this might pop up as an interview question ;)

What is casting or typecasting exactly?.

Now to be more technical casting can be done using a Cast Expression.

A Cast expression is used to perform an explicit conversion from one type to another.

So let’s see an example of a cast expression.

A cast expression of the form (T)E performs an explicit conversion of the result of expression E to type T.

The main difference between the convert and the parse methods are the following:

Convert takes an object as an input/argument where parse takes a string.

The convert methods will never throw an ArgumentNullException if you passed null as an argument, it will simply return the default value for the value type you are trying to convert to, for example 0 for integers, where Parse will throw an exception if you pass it null.

Now when it comes to converting strings both the convert and the parse methods will do the same thing, so in that case I recommend using Parse/TryParse.

But…

If you are dealing with your own custom types then, you can implement the IConvertible interface to provide your own implementation and use the Convert method to convert from other types to your own custom types.





tutorialsEU offers you free video tutorials about programming and development for complete beginners up to experienced programmers.
This includes C#, Unity, Python, Android, Kotlin, Machine Learning, etc.
Stay tuned and subscribe to tutorialsEU: https://goo.gl/rBFh3x

Комментарии

Информация по комментариям в разработке