Is there a way to specify in type parameters that a parameter is the type of the object instance?
For instance, to illustrate, I have:
public abstract class Model
{
public int Prop1 { get; set; }
}
For my example, I want to have a method that will return a property of the Model passed in (obviously this is a stupid method, but it gets the point across). I can make it work as an extension method:
public static class Extensions
{
public static U Property<T, U>(this T model, Expression<Func<T, U>> property) where T : Model
{
return property.Compile().Invoke(model);
}
}
this way I can have
public class DerivedModel : Model
{
public string Prop2 { get; set; }
}
and do
var myString = new DerivedModel().Property(a => a.Prop2);
This method seems like it should be part of the Model class, and look something like:
public T Property<T>(Expression<Func<ThisDerivedInstanceOfModel, T>> property)
{
return property.Compile().Invoke(this);
}
so that the same call to Property() that the extension method does can execute on an instance of a Model.
I realize that this is kind of bizarre and may simply not be a feature of C#, and the workaround extension method works perfectly well – but I’d much prefer to make this an instance method if possible, since seems ‘better’ to me.
Nope. Sorry. There are times when I can see it being useful, but it’s not something you can do. I’ve had similar issues in the past 🙁