Please excuse me if I am missing something (will delete if thats the case) but using an invalid cast like this:
struct Item
{
public int ID { get; set; }
public Derived Derived { get; set; }
}
public class Base
{
public string Name { get; set; }
}
public class Derived : Base
{
public string AdditionalProperty { get; set; }
}
var baseClass = new Base()
{
Name = "foo",
};
try
{
var x = new Item()
{
ID = (int)20,
Derived = (Derived)baseClass,
};
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
neatly catches the error like this
Unable to cast object of type 'Base' to type 'Derived'.
in vs2017
However this breaks on the first error, we might wanna initalize an object this way and log all cast errors withouth exiting the initialisation. We can do this by implementing our own casting for this sample:
public static T TryCast<T>(Object _object)
{
try
{
return (T)_object;
}
catch (Exception e)
{
Console.WriteLine($"Cant cast object of type {_object.GetType().ToString()} to object of type {typeof(T)}");
}
return default(T);
}
public static T TryCast<T>(IConvertible _object)
{
try
{
return (T)Convert.ChangeType(_object, typeof(T));
}
catch (Exception e)
{
Console.WriteLine($"Cant convert object of type {_object.ToString()} to object of type {typeof(T)}");
}
return default(T);
}
New types for demonstrating purposes
struct Item
{
public int ID { get; set; }
public double FooDouble { get; set; }
public Base Base { get; set; }
public Derived Derived { get; set; }
public string Bar { get; set; }
}
public class Base
{
public string Name { get; set; }
}
public class Derived : Base
{
public string AdditionalProperty { get; set; }
}
We can then initalize our object like this:
var derived = new Derived()
{
Name = "DerivedFoo",
AdditionalProperty = "Bar"
};
var _base = new Base()
{
Name = "BaseFoo"
};
var x = new Item()
{
ID = Utils.TryCast<int>("please no"),
FooDouble = Utils.TryCast<double>(2),
Base = Utils.TryCast<Base>(derived),
Derived = Utils.TryCast<Derived>(_base),
Bar = "Foo"
};
And we neatly log any errors that might occur when casting:
