First let’s establish this.
I have
public abstract class Foo
{
public static void StaticMethod()
{
}
}
public class Bar : Foo
{
}
is it valid to call
Bar.StaticMethod();
???
If so, let’s expand previous example:
public abstract class Foo
{
public static void StaticMethod()
{
}
public abstract void VirtualMethod();
}
public class Bar : Foo
{
public override void VirtualMethod()
{
Trace.WriteLine("virtual from static!!!!");
}
}
How should I construct StaticMethod in base class so I can use VirtualMethod from derived classes? It seems that I had too little/too much caffeine today and nothing comes to my mind here.
Hm, I know that I can’t invoke instance method from static method. So the question comes to this:
Can I create instance of derived class from static method of base class. By using something like:
public static void StaticMethod()
{
derived d=new derived();
d.VirtualMethod();
}
I invented new keyword, derived, for the purpose of illustration.
BTW, I will favor non-reflection based solution here!
To invoke a non static method from a static method, you have to provide an instance as the static method isn’t bound to
thisThen, after your edit, your question made me think of the curiously recurring template pattern in C++.
I never tried myself to use it in C# but you have have a look here, which would give you something like:
And prints out the intended
"virtual from static!!!!"message in the console.