Paul Zahra Paul Zahra - 2 months ago 6
C# Question

'T' does not contain a definition

Is it possible to do the following (If so I can't seem to get it working.. forgoing constraints for the moment)...

If the type (because it's ommitted) is inferred, what's the problem?

private void GetGenericTableContent<T>(ref StringBuilder outputTableContent, T item)
{
outputTableContent.Append("<td>" + item.SpreadsheetLineNumbers + "</td>");
}

// 'item' is either DuplicateSpreadsheetRowModel class or SpreadsheetRowModel class


With the above code I get the following error:


'T' does not contain a definition for 'SpreadsheetLineNumbers' and no extension method 'SpreadsheetLineNumbers' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?)

Answer

No, it's not possible. Generic types must be known at compile time. How could compiler know that it is guaranteed that T has SpreadsheetLineNumbers property ? What if T is int or an object ?

What prevents us from calling method with ref stringBuilder, 999 parameters ?

So it'd only work if you add interface with this property :

public interface MyInterface 
{
    string SpreadsheetLineNumbers { get; set; }
}

And make your class to inherit from this interface

public class MyClass : MyInterface
{
    public string SpreadsheetLineNumbers { get; set; }
}

And then use generic constraints to let compiler know that this type is inherited from this interface and therefore it must contain all its properties.

private void GetGenericTableContent<T>(ref StringBuilder outputTableContent, T item) 
    where T : IMyInterface // lets compiler know that T type has implemented all members of the interface
{
    outputTableContent.Append("<td>" + item.SpreadsheetLineNumbers + "</td>");
}
Comments