Casting and Convert method in C#
Hello guys, sorry to disturb you all; I just have a little question. Consider the following:
My question is, notice that we can cast an int to a double (upcasting) or cast a double to an int (downcasting). But why can't we cast a string representing a number into an it? Why in such cases we should use the Convert.ToInt method?
What is the difference between casting and convert?
35 Replies
int.Parse
What you wrote there is not valid
casting is not the same as parsing
$tryparse
When you don't know if a string is actually a number when handling user input, use
int.TryParse
(or variants, e.g. double.TryParse
)
TryParse
returns a bool
, where true
indicates successful parsing.
- Avoid int.Parse
if you do not know if the value parsed is definitely a number.
- Avoid Convert.ToInt32
entirely, this is an older method and Parse
should be preferred where you know the string can be parsed.
Read more hereyeah I had a doubt about that, I'm a beginner, can you explain why this is invalid syntax pls
what is the difference between casting and parsing pls
ero
REPL Result: Failure
Exception: CompilationErrorException
Compile: 254.710ms | Execution: 0.000ms | React with ❌ to remove this embed.
casting refers to number conversions and pointer (reference) conversions
parsing means extracting information from a string arranged in a certain way
a string that looks like a number in base 10 can be parsed into a number
this is not really true because you can define cast operators
More generally, casting means converting from one type to another. The types must be compatible in some way, maybe through inheritance or because an implicit or explicit conversion operator is defined on the types.
Parsing means interpreting some input so that it can become another type entirely, even if the two types were never compatible to begin with.
for your own types
They don't have to be specifically about integers or strings
meant number here, my bad
Not even that
You can cast any struct type as well, which would be neither of your cases
.
but if you ignored the ability to overload cast operators, in its basic sense, it deals with numbers and references
that is what is built in
Should point out that by default, casting is only possible if you attempt to cast an object to its type, or an inherited type. Anything else would throw an exception
You can extend casting which will allow you to add behaviour on what it should to do turn into a type.
yep noted, so basically casting is converting compatible data type from one type to another; what I mean by compatible is like the value we are trying to compare to should have the "same family" like converting an int to a double or vice versa. Similarly, we can cast references if they have an inheritance relationship.
Parsing mean converting a text into something logical, like a string to an int ?
Casting is not converting data unless you explicitly specify the cast has to do that
Otherwise it's nothing more than changing it to a compatible type, either because the object is that type, or inherited from that type
Most classes have a
ToX
method for converting to a different type, such as ToArray
There are also AsX
methods for more safer casting to known similar typesyeah i'd say implicit casts (int to double) shouldn't convert. explicit casts (double to int) can mean that conversion and therefore loss of data occurs.
Here I can do
AsEnumerable
since the collection uses the IEnumerable interface
ToX
allocates, whereas AsX
just changes it to that type. I could also do (IEnumerable<T>)ChatList
and it would work the same
There's also ChatList as IEnumerable<T>
in which case it casts, but it will turn nullable. The idea is that if a cast fails, then it will instead change to null
Lastly, there is pattern matching. Just google this. An example is ChatList is IEnumerable<T>
or ChatList is IEnumerable<T> enumerableChatList
And T in all cases is ChatListItemViewModel
but I am too lazy to type this outhmm what do we mean here, implicit casts, like int to double should not convert
Generally you should just stick to pattern matching since it works a ton easier than casting. Your code is more fluent
An implicit cast means you assign a type to a different type, but casting is not required.
This is valid
ero
REPL Result: Success
Compile: 194.179ms | Execution: 19.048ms | React with ❌ to remove this embed.
this implicitly casts
i
to double
Explicit means explicitly mentionin the type, like
IEnumerable<T> foo = (IEnumerable<T>)ChatList;
yeah I see but what do we mean by "shouldn't convert"
I mean both are casts, right?
Just read this: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/user-defined-conversion-operators
User-defined explicit and implicit conversion operators - provide c...
Learn how to define custom implicit and explicit type conversions in C#. The operators provide the functionality for casting an object to a new type.
i was trying to add something complementary to this statement, which i don't really agree with, but wanted to make sense of it for you
no matter what kind of cast, a conversion always happens
Yeah I see
I will just read the doc 2sec
Conversion sounds like you do work to make sure the type matches. Like with the example, having to create a class
But a cast is just simply changing the type to be an underlying type unless you change its behaviour
No allocation or conversion is done under the hood, you literally just give it a different compatible type
it's still a type of conversion
Which, again, sounds like you do more than just changing the type
I should say that you really should not add custom casting unless it is truly compatible types. This behaviour is often not documented and/or not something you easily figure out. It is also adviced you also add
ToX
or AsX
methods to a specific type for clarity, since intellisense picks up on those more clearlybut at this point we're arguing semantics really
Custom casting operators that do get implemented often also just call those
ToX
and AsX
methods in general
I think the example code is bad because of that. They should have also added ToDigit
and such
But either way, it's clear how it worksI have a basic and clearer understanding of how casting and conversion work, I believed I understood the basics, thanks guys 👍 ,if I have more doubts, will come back but I believe should be ok for now
yeah, was thinking it like classes of Animal, Dog and Cat, makes more sense when you say "it simply changes the type to be an underlyting type"