I’ve got a LINQ query in VB:
Dim ss = _someClassDataSource.Sum(Function(s) TryCast(s, SomeClass).BreakdownCover)
where BreakdownCover‘s type is string. When I’m trying rewrite it in C#:
var ss = _someClassDataSource.Sum(s=>s.BreakdownCover);
I get the exception:
Cannot implicitly convert type 'string' to 'int'
How can I deal with this problem?
use Int.Parse, don’t cast a string to an int
If you’re doing VB.NET then use
Here is why you can’t cast string to int:
It would potentially be better to not use Convert.ToInt32() because Convert.ToInt32 will still return a value when the string is null while int.Parse will throw. You might get unexpected results with Convert.ToInt32. Also see this question Whats the main difference between int.Parse() and Convert.ToInt32
Of course, this is based on the context as @Andy has pointed out. If you are ok with NULL being treated as 0 then either method will work.