❔ How to make a generic class property nullable?

I'm trying to have a generic interface with a nullable property:
public interface IMayHaveCreator<TKey>
{
TKey? CreatorId { get; set; }
}
public interface IMayHaveCreator<TKey>
{
TKey? CreatorId { get; set; }
}
But this doesn't work, as when I add it to a class, it gives an error when I try to make the implementation nullable aswell:
public class Foo : IMayHaveCreator<Guid>
{
public Guid? CreatorId { get; set; }
}
public class Foo : IMayHaveCreator<Guid>
{
public Guid? CreatorId { get; set; }
}
I says that Foo doesn't implement CreatorId, and it only works when I have it as Guid CreatorId Any idea why this doesn't work? is it even possible to this is C#? 🤔
5 Replies
Thinker
Thinker2y ago
Since TKey isn't constrained to anything, if you have IMayHaveCreator<Guid> then the CreatorId will just have the type Guid, not a nullable one If you were to do where TKey : struct then you would be able to have Guid?, but then you could not use IMayHaveCreator with reference types. This is just an inherent limitation of how nullables are implemented in C#, sadly.
youssefhabri
youssefhabriOP2y ago
I see. Thank you. Adding where TKey: struct works for me for now. If the issue with reference types becomes and issue in the issue, I'll find another solution @🌈 Thinker 🌈 Thank you again 😃
Thinker
Thinker2y ago
np catsip
Anton
Anton2y ago
where TKey : notnull should also work
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server