Answers for "add a 'protected' constructor or the 'static' keyword to the class declaration program.cs"

0

add a 'protected' constructor or the 'static' keyword to the class declaration program.cs

public class Program
{
    protected Program()
    {
        // Do something.
    }

    public static Program Create()
    {
        // 100% Allowed.
        return new Program();
    }

    public void DoSomething()
    {

    }
}

public static class AnotherClass
{
    public static Program CreateProgram()
    {
        // Not allowed since Program's constructor is protected.
        return new Program();
    }
}

public class SubProgram : Program
{
    protected SubProgram()
    {
        // Calls Program() then SubProgram().
    }

    public new static Program Create()
    {
        // return new Program(); // We would need to move the SubProgram class INSIDE the Program class in order for this line to work.
        return new SubProgram();
    }
}

Program.Create();               // Can be called since Create is public and static function.
Program.DoSomething()           // Can't be called because an instance has not been instantiated.
var test = Program.Create();
test.DoSomething();             // Can be called since there is now an instance of Program (i.e. 'test').
AnotherClass.CreateProgram();   // Can't be called since Program's constructor is protected.
SubProgram.Create();            // Can be called since SubProgram inherits from Program.
Posted by: Guest on October-28-2020

Code answers related to "add a 'protected' constructor or the 'static' keyword to the class declaration program.cs"

Browse Popular Code Answers by Language