Question

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!

Was it helpful?

Solution

To invoke a non static method from a static method, you have to provide an instance as the static method isn't bound to this

Then, 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:

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;

namespace ConsoleApplication3
{
  public abstract class Foo<T> where T : Foo<T>, new()
  {
    public static void StaticMethod()
    {
      T t = new T();
      t.VirtualMethod();
    }

    public abstract void VirtualMethod();
  }

  public class Bar : Foo<Bar>
  {
    public override void VirtualMethod()
    {
      System.Console.WriteLine("virtual from static!!!!");
    }
  }
  class Program
  {
    static void Main(string[] args)
    {
      Bar.StaticMethod();
    }
  }
}

And prints out the intended "virtual from static!!!!" message in the console.

OTHER TIPS

is it valid to call Bar.StaticMethod();???

Yes, calling Bar.StaticMethod is legal, and simply behaves as though you called Foo.StaticMethod.

Can I create instance of derived class from static method of base class.

OK, I think I understand what you want. You want to call a static method and have it create an instance of an ARBITRARY derived class, and then call a method on that class, yes?

Use generics.

abstract class Foo 
{
    public static void DoBlah<T>() where T : Foo, new()
    {
        T t = new T();
        t.Blah();
    }
    public abstract void Blah();
}
class Bar : Foo
{ 
    public Bar() {}
    public override void Blah() {}
}
...
Foo.DoBlah<Bar>();

Yes?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top