© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
72 replies
Pannekoekje

Casting, reflection or?

I'm trying to write a simple lib for consuming a few JSON API endpoints and processing their contents with callbacks.

I'm trying to cast the "parsed" variable to its actual class (as it is known during runtime). Psuedo code as follows:

public interface IType
{
    public string Type { get; set; }
}

public class TypeA : IType
{
    public string Type { get; set; }
    public string FancyA { get; set; }
}

public class TypeB : IType
{
    public string Type { get; set; }
    public string FancyB { get; set; }
}

void Get(json)
{
    var x = GetJson;
    IType returnObject = null;

    switch(x.GetType)
    {
        "TypeA":
            returnObject = JsonSerializer.Deserialize<TypeA>(x);
            break;
        "TypeB":
            returnObject = JsonSerializer.Deserialize<TypeB>(x);
            break;
    }
    return returnObject;
}

void DoParse()
{

    var callbacks = Dictionary<string, Action<IType>> { ("TypeA", DoStuffTypeA) };

    while(true)
    {
        var content = Retrieve();
        var parsed = Get(content);

        var callback = callbacks[parsed.Type]
        callback.Invoke(parsed)
    }
}

// Works
void DoStuffTypeA(IType content)
{
    //...    
}


// Doesn't work
void DoStuffTypeA(TypeA content)
{
    //...
}
public interface IType
{
    public string Type { get; set; }
}

public class TypeA : IType
{
    public string Type { get; set; }
    public string FancyA { get; set; }
}

public class TypeB : IType
{
    public string Type { get; set; }
    public string FancyB { get; set; }
}

void Get(json)
{
    var x = GetJson;
    IType returnObject = null;

    switch(x.GetType)
    {
        "TypeA":
            returnObject = JsonSerializer.Deserialize<TypeA>(x);
            break;
        "TypeB":
            returnObject = JsonSerializer.Deserialize<TypeB>(x);
            break;
    }
    return returnObject;
}

void DoParse()
{

    var callbacks = Dictionary<string, Action<IType>> { ("TypeA", DoStuffTypeA) };

    while(true)
    {
        var content = Retrieve();
        var parsed = Get(content);

        var callback = callbacks[parsed.Type]
        callback.Invoke(parsed)
    }
}

// Works
void DoStuffTypeA(IType content)
{
    //...    
}


// Doesn't work
void DoStuffTypeA(TypeA content)
{
    //...
}


Is this just impossible or am I implenting this stuff wrong?
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements
Next page

Similar Threads

❔ ASP.NET Core, OrchardCore, OrchardCMS
C#CC# / help
3y ago
❔ System.Reflection
C#CC# / help
4y ago
✅ Type Casting
C#CC# / help
4y ago
❔ ✅ Use Reflection or Generics to specify one or more properties
C#CC# / help
3y ago