Raj
Raj

Reputation: 4435

Initializing a class when using Generics

I've a Document class which has two overloads taking one parameter each (String and Stream). Why can't I use the following code to initialize Document class using Generics?

    public abstract class PdfDocumentEditBaseService<T> : IDocumentEditService<T>

    public T Rotate(T file, int pageNumber, float angle)
    {
        Document document = new Document(file); // cannot convert from 'T' to 'Stream'
        document.Pages[pageNumber].Rotation = (RotationMode)angle;
        document.SavePage(pageNumber);
        return file;
    }

Upvotes: 3

Views: 286

Answers (4)

John Gietzen
John Gietzen

Reputation: 49534

You can do that if you change your declaration to:

public abstract class PdfDocumentEditBaseService<T> : IDocumentEditService<T> where T : Stream

Upvotes: 3

Joel Coehoorn
Joel Coehoorn

Reputation: 415600

I see a few suggestions to require T to inherit from Stream. And that will work. But, if your T really is always a stream, why not just remove the generic parameter and build that class like this:

public abstract class PdfDocumentEditBaseService : IDocumentEditService
{
    public Stream Rotate(Stream file, int pageNumber, float angle)
    {
        Document document = new Document(file); 
        document.Pages[pageNumber].Rotation = (RotationMode)angle;
        document.SavePage(pageNumber);
        return file;
    }

Upvotes: 1

Oded
Oded

Reputation: 498904

You need to add a type constraint to your class declaration:

public abstract class PdfDocumentEditBaseService<T> : IDocumentEditService<T>
                                            where T : Stream

Upvotes: 2

Jeff Hornby
Jeff Hornby

Reputation: 13640

The problem seems to be that the constructor for the Document class requires an argument that is a Stream or derived from Stream. As the code is written there is no guarantee that T will be a Stream.

If you add a type constraint to the class declaration this should work:

public abstract class PdfDocumentEditBaseService<T> : IDocumentEditService<T> where T : Stream

Upvotes: 0

Related Questions