Static/new function new performing as expected

T

Thomas Fritzen

I have a problem with static functions and inheritance as demonstrated by the below samples

using System;
namespace ConsoleApplication1
{
class x
{
public static void Log()
{
Console.WriteLine("x.Log()");
}

public static void DoLog()
{
Log();
}
}

class y : x
{
public static new void Log()
{
Console.WriteLine("y.Log()");
}
}

class Class1
{
[STAThread]
static void Main(string[] args)
{
y.DoLog();
}
}
}

I was hoping that this program would output "y.log", since I call the "y" inherited static method
but instead it output "x.log", because the DoLog() method is binding to the "local" static

Can I do something to the code in my "x" class to make it call y - while still using static functions?
I do not want to override all the "DoLog"-like functions in my x class.
I know that this would work for non-static functions e.g.:

using System;
namespace ConsoleApplication1
{
class x
{
public virtual void Log()
{
Console.WriteLine("x.Log()");
}

public void DoLog()
{
Log();
}
}

class y : x
{
public override void Log()
{
Console.WriteLine("y.Log()");
}
}

class Class1
{
[STAThread]
static void Main(string[] args)
{
new y().DoLog();
}
}
}

Rgds,
Thomas Fritzen
 
P

Patrick Steele [MVP]

I have a problem with static functions and inheritance as demonstrated by the below samples

<snip>

Static members are not inherited. Static members are members of the
type itself, not an instance of the type.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top