Mike Lenart
Mike Lenart

Reputation: 939

How can I ensure that a Type of my class is a particular type during defining a subclass?

Say I have a base class of:

public abstract class BaseEntity<TId>
{
     private TId ID;
}

I want to ensure the TId types are either Guid/int/longs. How can I do that?

Upvotes: 1

Views: 406

Answers (2)

Scott Hannen
Scott Hannen

Reputation: 29202

Right now you can't do that. You're limited to these generic type constraints.

If you could require TId to be int, long, or Guid, the resulting inheritance would be weird. One entity would only be able to inherit from another if both used an ID of the same type.

Eventually you might find that you want to add a method into your abstract class. In that case it's unclear what the expected type or behavior of TId would be, because the abstract class doesn't know whether it's an int, long, or Guid. That would be a frustrating problem to run into after you've already built classes that inherit from the abstract class.

One solution is to decide in advance: How will my entities use the ID? How will other classes that interact with the entity use the ID? Having determined that, create an interface or class just for ID instead of using a primitive type. Perhaps that ID type only needs methods for

  • Generating a new ID
  • Comparing two IDs for equality
  • Creating a string representation of the ID for use in queries

Now the type of the ID - int, long, Guid - is encapsulated within the ID itself. Nothing outside of that ID type needs to know how the ID value is represented. It could even be multiple values. Perhaps at some point you need to add a country code or something similar, and now you can do that with fewer changes to dependent code because of that encapsulation.

I'm imagining other ways to do it, like using an enum that specifies which type the ID is, but it all gets complicated and messy. So if you must work within this constraint that any of these types of values can be used to store IDs, I'd consider creating an ID type. But if there's any way to avoid having this problem, that would be my first choice.

Upvotes: 3

Felix
Felix

Reputation: 10078

In the future you will be able to define a type as Union:

Type TId = Guid | int | long

and then you can simply have

private TId ID;

But when? Who knows. https://github.com/dotnet/csharplang/issues/113

Upvotes: 0

Related Questions