I'm trying to create an interface that will add a column to a database entity which will be used the track the user making changes.
public interface IAuditEntity<TKey>
{
TKey? UpdatedBy { get; set; }
}
The interface will be used by different applications. So 1 application could use an integer as a key and another might use a string.
However, as it's a nullable type I get the following error: A nullable type parameter must be known to be a value type or non-nullable reference type. Consider adding a 'class', 'struct', or type constraint.
How can I achieve this so I can use both value and reference types? So int or string really?
Thanks.
CodePudding user response:
If your goal is just to have a generic type parameter that can be a reference type, value type, or nullable value type. Just remove the ?
public interface IAuditEntity<TKey>
{
TKey UpdatedBy { get; set; }
}
public class Bob : IAuditEntity<int?>
{
public int? UpdatedBy { get; set; }
}
If you are trying to use the nullable reference type feature, you will need to bump the version of your project
<LangVersion>9.0</LangVersion>
<nullable>enable</nullable>
Be warned : This is not fully supported, and likely to cause issues with certain language features, and not all attributes will be useable.
If your goal is to use reference types and value types, where the generic parameter is known to be a not nullable value type, and the reference types can be null
, in C#8 or later you can use the notnull
constraint without the ?
public interface IAuditEntity<TKey> where TKey : notnull
{
TKey UpdatedBy { get; set; }
}
If you would want to use reference types and value types, where the generic parameter is known to be not nullable, and the reference types can be null
and also use the nullable reference type feature, you can use the notnull
constraint and the nullable type operator ?
C#9 or later
public interface IAuditEntity<TKey> where TKey : notnull
{
TKey? UpdatedBy { get; set; }
}