2

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?

ckittel
  • 6,478
  • 3
  • 41
  • 71
user278618
  • 19,306
  • 42
  • 126
  • 196
  • 3
    In general, translating from VB.NET to C# is *immensely* easier if you first make the VB.NET work with `Option Explicit On` and `Option Strict On`. – AakashM Aug 26 '11 at 14:40
  • 3
    Then again if you knew to program with those on, you'd probably be using a type-safe language in the first place... – Blindy Aug 26 '11 at 14:46

2 Answers2

6

use Int.Parse, don't cast a string to an int

var ss=_someClassDataSource.Sum(s=>int.Parse(s.BreakdownCover));

If you're doing VB.NET then use

var ss=_someClassDataSource.Sum(s=>Integer.Parse(s.BreakdownCover));

Here is why you can't cast string to int:

Because the explicit cast isn't implemented... ToString() is a general method (implemented in System.Object) and if string would implement the cast that would beg the question if all other classes need to implement it too...

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.

Community
  • 1
  • 1
Dustin Davis
  • 14,482
  • 13
  • 63
  • 119
  • You could argue that it would be beneficial to use Convert.ToInt32 as a null string will be treated as 0 and not cause and exception and return a result. Which one is better really depends on the context of the problem. In either case it will blow up if the string is "abc". – Andy Rose Aug 26 '11 at 14:58
  • @DustingDavis - no problem, ultimately the best solution would be to use a non nullable numeric field in the database in the first place ;-) – Andy Rose Aug 26 '11 at 15:05
4

You need to explicitly convert the string to an int:

var ss=_someClassDataSource.Sum(s=> Convert.ToInt32(s.BreakdownCover));

As pointed out by DustinDavis Convert.ToInt32 will return a 0 if the string is null. If you would rather an exception be thrown then Int32.Parse will be a better option. However if the field accepts nulls and if these should be treated as 0 then this will return the expected result.

Andy Rose
  • 16,770
  • 7
  • 43
  • 49
  • I think in this case with Sum() it would be ok, but not if it were Avg(). But again, depends on context. Good point. – Dustin Davis Aug 26 '11 at 15:03