Home > Net >  C# set a default for a type parameter
C# set a default for a type parameter

Time:11-13

I am trying to extend a class where I optionally want to pass in a type. However, more times than not this will be of type int although in some cases this can change so I want to make it dynamic.

However, I want to make it so it defaults to the integer type, and as this extends another class which needs the type, I wasn't sure how to approach it.

I have a BaseEntity setup, in order for me to allow CreatedAt and UpdatedAt columns to be populated when the record is created / updated, this extends the Identifiable class from the JSON API package.

class BaseEntity : Identifiable {
    ...
}

The Identifiable class, optionally allows you to pass in the type parameter to the extension if the type of the id is different than the original one specified.

class BaseEntity : Identifiable<Guid> {
    ...
}

I'm wondering, how can I extend this BaseEntity class and optionally provide a type and pass it in to the Identifiable. Is this achievable or would I need to supply it every time.

class BaseEntity<T> : Identifiable<T> {
  // <T> Should default to int if possible.
}
class AnotherEntity : BaseEntity<Guid> {
  // Allow me to pass in GUID to override the default int type
}
class AnotherEntityAgain : BaseEntity {
  // Would default to type <int> if nothing specified.
}

CodePudding user response:

There is no such thing in C# as an "optional type", that is achieved by having two classes, one with a type and one without. C# allows you to have both at the same time since ClassName is considered a different type to ClassName<T>

You can achieve the same by creating a type-less class like this:

class BaseEntity : Identifiable<int> {
  
}

You could also make the class inherit directly from your generic class so you don't need to duplicate code:

class BaseEntity : BaseEntity<int> {
  
}
  • Related