Inline constructor and InjectFrom calls return Object
-
27-06-2021 - |
Question
Using ValueInjecter, I often find myself writing code like this:
var foo1 = new Foo().InjectFrom(foo2);
But that, unexpectedly, causes foo1 to be of type Object, not Foo. Same with
var foo1 = (new Foo()).InjectFrom(foo2);
and
Foo foo1 = new Foo().InjectFrom(foo2);
won't compile. It's not a big deal, because I can easily do
var foo1 = (Foo)new Foo().InjectFrom(foo2);
or
var foo1 = new Foo();
foo1.InjectFrom(foo2);
and those both work as expected, but I'm curious. Why does the first way not work?
La solution
I haven't use ValueInjecter, but my suppose is that InjectFrom
method returns object value.
And as var
is sugar syntax, and autodefines variable type during compilation, this variable is defined as Object.
That's why you have to use explicit type convertion to make this work for you.
Autres conseils
Try to add custom extension method:
public static T InjectFrom<T>(this T obj, T from) //May be from should be object type
{
return (T) obj.InjectFrom(foo2);
}
You could write like this as well:
var foo1 = new Foo().InjectFrom(foo2) as Foo;
A couple of extensions:
public static class ValueInjecterExtentions
{
public static T InjectIntoNew<T,TInjection>(this object from)
where T: new ()
where TInjection : Omu.ValueInjecter.Injections.IValueInjection, new()
{
return (T) new T().InjectFrom<TInjection>(from);
}
public static T InjectIntoNew<T>(this object from)
where T : new()
{
return (T)new T().InjectFrom(from);
}
}
usage:
var foo = foo2.InjectIntoNew<Foo>();
obviously only usable with default constructor, which is often the case.