I’m facing a requirement to create a static method on my base class, but don’t like that I have to declare type arguments, so I’m wondering if I’m going about this the right way.
Basically, I’m assigning delegates that I’ll associate with properties on the class. I could easily put the method on the inherited classes, like so:
public class Foo
{
public string Property1 { get; set; }
}
public class InheritsFoo : Foo
{
public void AssignDel<TVal>(
Expression<Func<InheritsFoo, TVal>> expr,
Action<InheritsFoo, TVal> action)
{
}
}
Or, in an extension class, I could do this:
public static void AssignDel<T, TVal>(
this T source,
Expression<T, TVal>> expression,
Action<T, TVal> action)
where T : Foo
{
}
Both of these would enable me to use AssignDel in an instantiated class:
var foo = new InheritsFoo();
foo.AssignDel(x => x.Property1, handler);
But I have a requirement to make AssignDel static. This makes the extension way of doing it useless. It still works in InheritsFoo, but I really want to move this to the base class. If I try, the generics argument can’t be inferred, and I have to change the usage of the method:
InheritsFoo.AssignDel<InheritsFoo, string>(x => x.Property1, handler);
Is there a way out here, another way of doing this I haven’t thought of?
EDIT: to address the issue in the comments about whether or not the extension method would/should work… I went to the url referenced by @Mark M. Turns out that if I write it as such…
InheritsFoo foo = null;
foo.AssignDel(x => x.Property1, handler);
That compiles (don’t know if it will run, though). Still, don’t think that qualifies as using a static method, since ‘foo’ is still considered an instance; A null instance, but an instance nonetheless.
I managed to do what I needed by just implementing another level in the inheritance chain.
I can treat InheritsFoo just as I need it.