Casting good practice
Posted
by phenevo
on Stack Overflow
See other posts from Stack Overflow
or by phenevo
Published on 2010-04-06T07:52:10Z
Indexed on
2010/04/06
8:03 UTC
Read the original article
Hit count: 734
Hi,
I've got 3 classes
namespace ServerPart
public class Car
{
}
namespace ServerPart
public class SUV:Car
{
public string Name {get;set;}
public string Color {get;set;)
}
And
namespace WebSericePart
public class Car
{
}
namespace WebSericePart:Car
public class SUV
{
public string Name {get;set;}
public string Color {get;set;)
}
And I've translator
namespace WebServicepart.Translators
public static class ModelToContract
{
public Car[] ToCars(ServerPart.Car[] modelCars)
{
List<Car> contractCars=new List<Car>();
foreach(ServerPart.Car modelCar in modelCars)
{
contractCars.Add(ToCar(modelCar);
}
return contractCars.ToArray();
}
public Car ToCar(ServerPart.Car modelCar)
{
if(modelCar is ServerPart.SUV)
{
return ToSUV(modelCar);
}
else
{
throw new NotImplementedException("Not supported type of Car")'
}
}
public Car ToSUV(ServerPart.Car modelCar)
{
SUV suv=new SUV;
//
suv.Name=((ServerPart.SUV)modelCar).Name
suv.Color=((ServerPart.SUV)modelCar).Color
// ?? Is good practice ?? Or
//ServerPart.SUV suv=(ServerPart.SUV)modelCar
//suv.Name=suv.Name
//suv.Color=suv.Color
// is better ??
return suv;
}
}
Do I used some else bad practices ?? Or Everything is OK :) ?
© Stack Overflow or respective owner