Home > database >  Creating a property class with no default value and with value
Creating a property class with no default value and with value

Time:12-17

I'm trying to create a property class with a default value and no value. Is this right? If I want a property with no value I'll just call GameLevel class and if I want a property with default value I'll just call GameLevelWithDefaultValue

public abstract class GameLevel
{
    public abstract int nextLevelToUnlock { get; set; }

    public abstract List<LevelDetails> levelDetails { get; set; }
}

class GameLevelWithDefaultValue : GameLevel
{
    public override int nextLevelToUnlock { get; set; } = 1;

    public override List<LevelDetails> levelDetails { get; set; } = new List<LevelDetails>()
    {
        new LevelDetails{levelIndex = 1, Stars = 0 },
        new LevelDetails{levelIndex = 2, Stars = 0 },
        new LevelDetails{levelIndex = 3, Stars = 0 }
    };
}

public class LevelDetails
{
    public int levelIndex { get; set; }
    public int Stars { get; set; }
}

CodePudding user response:

I meant something like this:

public class GameLevel
{
    public int NextLevelToUnlock { get; set; }
    public List<LevelDetails> LevelDetails { get; set; }

    public GameLevel() { }

    public GameLevel(int nextLevelToUnlock, List<LevelDetails> levelDetails)
    {
        NextLevelToUnlock = nextLevelToUnlock;
        LevelDetails = levelDetails;
    }
}

public class LevelDetails
{
    public int LevelIndex { get; set; }
    public int Stars { get; set; }

    public LevelDetails(int levelIndex, int stars)
    {
        LevelIndex = levelIndex;
        Stars = stars;
    }
}

public static class GameLevelBuilder
{
    public static GameLevel BuildGameLevelWithDefaultValue()
    {
        var defaultLevelDetail = new List<LevelDetails>()
        {
            new LevelDetails(1, 0),
            new LevelDetails(2, 0),
            new LevelDetails(3, 0)
        };

        return new GameLevel(1, defaultLevelDetail);
    }
}

When you need the object with the default value, you'll let the GameLevelBuilder create the object for you, while when you need the object without passing the initial values, you'll use the parameterless constructor of GameLevel.

CodePudding user response:

You cannot instantiate an abstract class. If you inherit an abstract class, you must override it's abstract properties. So, the value of nextLevelToUnlock and levelDetails depends on the child class. Also, default value for class in C# is null, or the result of it's zero parameter constructor for value types. If you don't assign any value to a field, it will get it's default value.

  • Related