Tim
Tim

Reputation: 3803

C# return derived class in abstract class

I would like to create a NMEA message parser for GPGGA, GPGSV, and etc. Each of the message is derived from the abstract class NMEAMsg.

So I would need to overwrite the parseToken for each of the message type:

But, I do not know how to return the derived class in the abstract class?

I am getting Invalid CastException unhandled by user when run this code

I need the public static NMEAMsg parse(string src) method to return the derived class like GGA or GSA

//NMEAMsg.cs
public abstract class NMEAMsg
{
    public static NMEAMsg parse(string src)
    {
        NMEAMsg nmeaMsg = (NMEAMsg)new object();

        var tokens = src.Split(',');
        tokens[tokens.Length - 1] = tokens[tokens.Length - 1].Split('*')[0];

        nmeaMsg.parseTokens(tokens);

        return nmeaMsg;
    }

    public abstract void parseTokens(string[] tokens);
}


//GGA.cs
public class GGA : NMEAMsg
{
    public double latitude;
    public double longitude;

    public override void parseTokens(string[] tokens)
    {
        Double.TryParse(tokens[1], out this.latitude);
        Double.TryParse(tokens[2], out this.longitude);
    }
}

//GSA.cs
public class GSA : NMEAMsg
{
    public double hdop;

    public override void parseTokens(string[] tokens)
    {
        Double.TryParse(tokens[1], out this.hdop);
    }
}

//main.cs
string src = "$GPGGA,123,323*23";

var data = NMEAMsg.parse(src);

if (data is GGA) {
   //Do stuff here  
} else if (data is GSA) {
   //Do stuff here
}

Upvotes: 1

Views: 604

Answers (1)

sstan
sstan

Reputation: 36473

You'll probably need something like this:

public static NMEAMsg parse(string src)
{
    var tokens = src.Split(',');
    tokens[tokens.Length - 1] = tokens[tokens.Length - 1].Split('*')[0];

    NMEAMsg nmeaMsg = null;
    if (tokens[0] == "$GPGGA")
    {
        nmeaMsg = new GGA();
    }
    else if (tokens[0] == "$GPGSA")
    {
        nmeaMsg = new GSA();
    }
    else
    {
        throw new Exception("Unrecognized type: " + tokens[0]);
    }

    nmeaMsg.parseTokens(tokens);

    return nmeaMsg;
}

Where you instantiate the correct class based on the beginning of the parsed string, and then call the specific class' parseTokens() method implementation to complete the parsing.

Upvotes: 2

Related Questions