Does anyone know of some way to specify the current class type similar to the way you would use generics? Hard to word, example:
class Example
{
public Example DefaultExample;
}
only instead of stating the class explicitly, I would like some implicit way to do it such as:
class Example
{
public
}
So that child classes would automatically have a DefaultExample member of their own class type:
class ExampleChild : Example
{
void DoChildStuff()
{
Default.DoChildStuff()
}
}
i can sort of achieve this by doing the following:
class ExampleBase
{
public Type DefaultExample;
}
class ExampleChild : ExampleBase
{
}
class ExampleChildChild : ???
{
}
but obviously the inheritance breaks after the first level
Any ideas or is this just not feasible?
AlanPosted Apr 13, 2008, 5:58 AM
I don't think, Jared, that reflexive typing is feasible in a statically typed language such as C#.
In any case, I'd have thought that you wanted the 'DefaultExample' field to be static rather than instance which means that you need code to set it to an appropriate instance of the containing class. Something like the following:
using System;
class Test
{
static void Main()
{
Example ex = Example.DefaultExample;
Console.WriteLine(ex.Message);
ExampleChild exch = ExampleChild.DefaultExample;
Console.WriteLine(exch.Message);
Console.ReadKey();
}
}
class Example
{
static Example defaultExample;
public static Example DefaultExample
{
get
{
if (defaultExample != null) return defaultExample;
defaultExample = new Example();
defaultExample.Message = "This is a default example";
return defaultExample;
}
}
public string Message;
}
class ExampleChild : Example
{
static ExampleChild defaultExample;
new public static ExampleChild DefaultExample
{
get
{
if (defaultExample != null) return defaultExample;
defaultExample = new ExampleChild();
defaultExample.Message = "This is a default example child";
return defaultExample;
}
}
}