Reputation: 7931
I try to convert vb.net code to c# like below VB.NET
Dim _obj As Object = _srv.GetData(_criteria)
If _obj IsNot Nothing Then
For Each Comp As ComponentItem In DirectCast(DirectCast(_obj("ComponentInformation"), Result).Output, List(Of ComponentItem))
_lstComp.Add(New Core.Component() With {.ComponentID = Comp.BusinessUnitID, .ComponentName = Comp.BusinessUnitName})
Next
End If
C#
object obj = srv.GetData(criteria);
if (obj != null)
{
foreach (ComponentItem comp in (List<ComponentItem>)((Result)obj("ComponentInformation")).Output)
{
lstComp.Add(new Component
{
ComponentId = comp.BusinessUnitID,
ComponentName = comp.BusinessUnitName
});
}
}
after converting the code i got an error obj' is a 'variable' but is used like a 'method' How to reslove this error?
Upvotes: 0
Views: 607
Reputation: 37760
C#, prior to v 4.0, where dynamic
s were introduced, doesn't support late binding, like VB does:
_obj("ComponentInformation")
So, you can't just write something like this for variable of object
type:
_obj["ComponentInformation"]
in C# without dynamic
or reflection API (e.g., if you working with COM object).
You either have to declare variable of appropriate type (which has indexer), or use dynamic
, or use reflection API.
Upvotes: 0
Reputation: 223187
obj
is probably an array, in C# you have to access its members via square brackets []
. So it should be:
obj["ComponentInformation"]
EDIT: (courtesy @Groo)
You have to change your line:
object obj = srv.GetData(criteria);
Instead of object
you should specify the type which is being returned by the method. Or you can use var
to have an implicitly typed variable.
var obj = srv.GetData(criteria);
Upvotes: 4
Reputation: 19636
Change object
to var
:
var obj = srv.GetData(criteria);
And ...
For Each Comp As ComponentItem In DirectCast(DirectCast(_obj["ComponentInformation"], Result).Output, List(Of ComponentItem))
Upvotes: 1