C#C
C#2y ago
olayk

How to implement default indexing for my own JSONValue class

namespace JSONNS;

abstract class JSONValue;

class JSONNum(int val) : JSONValue {
    public int Val { get; set; } = val;
    public override string ToString() { return $"{Val}"; }
}

class JSONString(string val) : JSONValue {
    public string Val { get; set; } = val;
    public override string ToString() { return $"{Val}"; }
}

class JSONBool(bool val) : JSONValue {
    public bool Val { get; set; } = val;
    public override string ToString() { return $"{Val}"; }
}

class JSONNull : JSONValue {
    public static int? Val = null;
}

class JSONArray(List<JSONValue> val) : JSONValue {
    public List<JSONValue> Val { get; set; } = val;
}

class JSONObject(Dictionary<string, JSONValue> val) : JSONValue {
    public Dictionary<string, JSONValue> Val { get; set; } = val;
    public JSONValue this[string s] { get => Val[s]; }
}


In another file I have a Parser class with Parser.parse() returning a JSONValue or throwing an error.

Q1) If I have an abstract class as a return value / value does it enforces that it returns an instance of a child of this class?
Q2) If I want to be able to index an unknown JSONValue (e.g. json['key1]['key2']) how should I do this? Would it work to have an abstract method for indexing, which returns an error on types such as JSONNumber?
Q3) How could I enforce a Val in the JSONValue class? I would like to have a default ToString where I return the Val ToString which I would override on the JSONArray and JSONObject types, but I am not sure what type the Val could even be.
Q4) Would it be a good idea to create my own error types for parsing, lexing and json indexing?

Many thanks for any help! I'd appreciate any input on the code shown here also as I am new to C#. I'm not sure if this is the best way to create a type, so I'd appreciate any comments on a better way to implement this.
Was this page helpful?