Reputation: 13582
I have 2 project in my solution, a web-service
project and a win-forms
project. I want to cast returning data of web-service to win-forms data. I have class Terminal defined in both projects. In the win app I have written this cast:
static public implicit operator List<Terminal>(EService.Terminal[] svcTerminals)
{
List<Terminal> terminals = new List<Terminal>();
foreach (var svcTerminal in svcTerminals)
{
Terminal terminal = new Terminal();
terminal.TerminalID = svcTerminal.TerminalID;
terminal.TerminalTypeID = svcTerminal.TerminalTypeID;
terminal.TerminalGUID = svcTerminal.TerminalGUID;
terminal.Description = svcTerminal.Description;
terminal.Name = svcTerminal.Name;
terminal.PortID = svcTerminal.PortID;
terminals.Add(terminal);
}
return terminals;
}
but it does not work and gives the error user-defined conversion must convert to or from enclosing type, this happens for List cast. But in Terminal cast everything is ok
static public implicit operator Terminal(EService.Terminal svcTerminal)
{
Terminal terminal = new Terminal();
terminal.TerminalID = svcTerminal.TerminalID;
terminal.TerminalTypeID = svcTerminal.TerminalTypeID;
terminal.TerminalGUID = svcTerminal.TerminalGUID;
terminal.Description = svcTerminal.Description;
terminal.Name = svcTerminal.Name;
terminal.PortID = svcTerminal.PortID;
return terminal;
}
Can anyone help me fix this so that I can
return (List<Terminal>)eService.CheckTerminal(guid, ref cityName, ref portName);
Instead of
List<Terminal> terminals = new List<Terminal>();
var svcTerminals = eService.CheckTerminal(guid, ref cityName, ref portName);
foreach (var svcTerminal in svcTerminals)
{
Terminal terminal = new Terminal();
terminal.TerminalID = svcTerminal.TerminalID;
terminal.TerminalTypeID = svcTerminal.TerminalTypeID;
terminal.TerminalGUID = svcTerminal.TerminalGUID;
terminal.Description = svcTerminal.Description;
terminal.Name = svcTerminal.Name;
terminal.PortID = svcTerminal.PortID;
terminals.Add((Terminal)svcTerminal);
}
return terminals;
Upvotes: 2
Views: 204
Reputation: 301147
You can do:
eService.CheckTerminal(guid, ref cityName, ref portName).Select(x => (Terminal) x);
Upvotes: 4
Reputation: 26931
MSDN says
Either the type of the argument to be converted, or the type of the result of the conversion, but not both, must be the containing type.
So, for his to work you need to move your conversion operator declaration into the class you are converting to (or from), i.e. List<Terminal>
or EService.Terminal[]
. Since you can't add methods into a standard classes, I would recommend making this method rather than an operator, or using LINQ.
Upvotes: 0