Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# generic type in a base class

I'm writing a system that has a set of protocol buffers (using protobuf-net), I want to define something like this in an abstract class they all inherit off:

public byte[] GetBytes()

however, the protocol buffer serealiser requires a type argument, is there some efficient way to get the type of the inheriting class?

Example:

public byte[] GetBytes()
    {
        using (MemoryStream stream = new MemoryStream())
        {
            Serializer.Serialize<T /* what goes here? */>(stream, this);
            return stream.ToArray();
        }
    }
like image 925
Martin Avatar asked May 22 '26 04:05

Martin


2 Answers

Just write "T" right?

and then in your class declaration:

public class M<T>

?

-- Edit

And then when you inherit it:

public class Foo : M<Apple>
like image 139
Noon Silk Avatar answered May 24 '26 20:05

Noon Silk


You can do this via reflection, but protobuf-net did it for you.

Just change your call to:

Serializer.NonGeneric.Serialize(stream, this /* Takes an object here */);

This works by building the generic method at runtime via reflection. For details, check the code (second method here).

like image 43
Reed Copsey Avatar answered May 24 '26 20:05

Reed Copsey