I'm having a couple basic generics problems. Basically, I'm trying to identify

Discussion in 'C#' started by seo-india, Aug 27, 2010.

  1. #1
    I'm having a couple basic generics problems. Basically, I'm trying to identify a piece of content by two indexes.

    1) I need to store the content in the class, so I need to create a class variable, classTableCellContent, to store it in. Therefore I need to create one, requiring me to constrain the generic type "where ContentType : new()". However, when I attempt to consume this type with a string, e.g. TableCell<string>, it throws a compiler error "The type 'string' must have a public parameterless constructor in order to use it as a parameter blahblahblah..."

    2) I need to accept input, so I have an add function. However, when I try to indicate that the third parameter is the same data type, i.e. ContentType, the compiler seems to believe that I'm creating a "new" data type with a poorly chosen name that hides the original data type declared in the class declaration. I'm sure this must be something stupid I'm missing. All I want to do is accept an input variable of the generic type in a function and store it in the class for later use.

    Here's the code. I've even highlighted the two lines that seem to be throwing the errors.

    Code:

    public class TableCell<ContentType> where ContentType : new()
    {
    private int classRowIndex = 0;
    private int classColumnIndex = 0;
    private ContentType classTableCellContent = new ContentType();


    /// <summary>
    /// TableCell<ContentType>() - Constructors for creating a new TableCell
    /// </summary>
    public TableCell() {}
    public TableCell(int inputRowIndex, int inputColumnIndex, ContentType inputTableCellContent)
    {
    addContent<ContentType>(inputRowIndex, inputColumnIndex, inputTableCellContent);
    }


    /// <summary>
    /// void addContent<ContentType>(int inputRowIndex, int inputColumnIndex, ContentType inputTableCellContent) - accepts row and column indexesa dictionary and returns the XHTML to display all it's contents as a list
    /// </summary>
    public void addContent<ContentType>(int inputRowIndex, int inputColumnIndex, ContentType inputTableCellContent)
    {
    classRowIndex = inputRowIndex;
    classColumnIndex = inputColumnIndex;
    classTableCellContent = inputTableCellContent;
    }
    }
     
    seo-india, Aug 27, 2010 IP