For example, i have this:
class BasePacket
{
int header;
int type;
}
class ChildPacket1 : BasePacket
{
//...
}
class ChildPacket2 : BasePacket
{
//...
}
BasePacket bp;
Type t;
object obj = CreateNeededChildPacket(out t); //return one of childs as object and it's real type
bp = ...// anyway to cast obj to type represented by t? or by using something else?
In your example you are creating one of two derived classes and storing it in a base variable…this does not require any casting at all as it is perfectly fine to do this per the laws of inheritance. A base-type variable can always be assigned a more derived object since anything the base class would be able to do it is guaranteed the derived class can do as well, so it is safe. For example, a Math teacher can perform any action a regular Teacher can (such as GradePapers()). It would be safe to point a Math Teacher object with a Teacher variable.
Edit:
In response to your comment, Ideally you would have the CreateNeededChildPacket() method return a BasePacket type (if the returned object is always dervied from BasePacket). Just as a base parameter can accept a derived object, a base return type can return a derived object, this is the beauty of inheritance. This would be much safer for someone down the road calling your method.
If you cannot update the method then you could add some additional type-checking just to be safe.