I am looking for a C# equivalent of a Java idiom.
In Java, if you have an abstract class, you cannot directly create an object of that class; you need to subclass it (and provide an override of the abstract methods) first. But you can actually create the subclass and object at the same time:
public abstract class Type {
abstract Kind kind();
public static final Type BOOLEAN =
new Type() {
@Override
Kind kind() {
return Kind.BOOLEAN;
}
};
The above doesn't translate verbatim into C#; is there an equivalent idiom? Or do you just need to write it out longhand, declaring a named subclass first, then creating an object of the subclass?
CodePudding user response:
Unfortunately not. Maybe you can try making a private class which implements your class Type
and then make a method that returns that?
However, maybe take a look at what you're trying to implement. This might not be the right pattern for your problem.
public abstract class Type
{
public abstract string Kind();
public static Type BOOLEAN()
{
return new BooleanType();
}
private class BooleanType : Type
{
public override string Kind()
{
return "Boolean";
}
}
}