0
votes

I came across the following code, which is creating an instance of base class (AbstractClassType):

AbstractClassType myVariable = someClassTypeArg.anotherClassTypeVar.EnumTypeVariable switch
{
    AnotherEnumType.enum1 => new DerivedClass_1_FromAbstractClassType(),
    AnotherEnumType.enum2 => new DerivedClass_2_FromAbstractClassType(),
    _ => throw new Exception("The provided enum is not valid"),
};
var computeThisVariable = myVariable.GetKeyData(something, anotherThing);

I am quite confused with the above code. Why the Switch statement is used (which C# concept is it...)?

This isn't a switch statement - it's a switch expression, introduced in C# 8. See docs.microsoft.com/en-us/dotnet/csharp/language-reference/…Jon Skeet
"creating an instance of base class" - Probably not. If the name is any indication, that class is abstract so it can't be instantiated. What this is doing is instantiating one of the derived classes and returning a base class reference.madreflection
The switch expression is used to determine whether DerivedClass_1_FromAbstractClassType or DerivedClass_2_FromAbstractClassType has to be created based on an enum value.Olivier Jacot-Descombes
@madreflection: Thanks for the clarification. Yes, the abstract class cannot be instantiated. I chose wrong selection of words ;)skm
@madreflection: Right. Just wondering, what should we call AbstractClassType myVariable? Is the variable myVariable an instance of AbstractClassType or an instance of the DerivedClass? If I say that myVariable is an instance of the class DerivedClass, wouldn't it be misleading too?skm