C
C#2d ago
Faker

Casting and Convert method in C#

Hello guys, sorry to disturb you all; I just have a little question. Consider the following:
C#
int num1 = 20;
num1 = (double) 20.0;

string num2 = "20";
num2 = (int) "20";
C#
int num1 = 20;
num1 = (double) 20.0;

string num2 = "20";
num2 = (int) "20";
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
Anton
Anton2d ago
int.Parse
ero
ero2d ago
What you wrote there is not valid
Anton
Anton2d ago
casting is not the same as parsing
ero
ero2d ago
$tryparse
MODiX
MODiX2d ago
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)
if (int.TryParse("123", out int number))
{
var total = number + 1;
Console.WriteLine(total); // output: 124
}
if (int.TryParse("123", out int number))
{
var total = number + 1;
Console.WriteLine(total); // output: 124
}
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 here
Faker
FakerOP2d ago
yeah 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
MODiX
MODiX2d ago
ero
REPL Result: Failure
int i = (double)20.0;
int i = (double)20.0;
Exception: CompilationErrorException
- Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?)
- Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?)
Compile: 254.710ms | Execution: 0.000ms | React with ❌ to remove this embed.
Anton
Anton2d ago
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
ero
ero2d ago
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.
Anton
Anton2d ago
for your own types
ero
ero2d ago
They don't have to be specifically about integers or strings
Anton
Anton2d ago
meant number here, my bad
ero
ero2d ago
Not even that You can cast any struct type as well, which would be neither of your cases
Anton
Anton2d ago
. 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
FusedQyou
FusedQyou2d ago
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.
Faker
FakerOP2d ago
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 ?
FusedQyou
FusedQyou2d ago
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 types
FusedQyou
FusedQyou2d ago
No description
ero
ero2d ago
yeah 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.
FusedQyou
FusedQyou2d ago
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 out
Faker
FakerOP2d ago
hmm what do we mean here, implicit casts, like int to double should not convert
FusedQyou
FusedQyou2d ago
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.
int foo = 5;
double bar = foo;
int foo = 5;
double bar = foo;
This is valid
MODiX
MODiX2d ago
ero
REPL Result: Success
int i = 20;
double d = i;
int i = 20;
double d = i;
Compile: 194.179ms | Execution: 19.048ms | React with ❌ to remove this embed.
ero
ero2d ago
this implicitly casts i to double
FusedQyou
FusedQyou2d ago
Explicit means explicitly mentionin the type, like IEnumerable<T> foo = (IEnumerable<T>)ChatList;
Faker
FakerOP2d ago
yeah I see but what do we mean by "shouldn't convert" I mean both are casts, right?
FusedQyou
FusedQyou2d ago
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.
ero
ero2d ago
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
Faker
FakerOP2d ago
Yeah I see I will just read the doc 2sec
FusedQyou
FusedQyou2d ago
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
ero
ero2d ago
it's still a type of conversion
FusedQyou
FusedQyou2d ago
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 clearly
ero
ero2d ago
but at this point we're arguing semantics really
FusedQyou
FusedQyou2d ago
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 works
Faker
FakerOP2d ago
I 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"

Did you find this page helpful?