C
C#3w ago
Ruttie

Inline if conditionals in dotnet new template

I have a class like the following:
public class MyTemplateClass : BaseClass {
public class MyTemplateClass : BaseClass {
I want to add a parameter to the template to make the class inherit a specific interface. If I do this using:
public class MyTemplateClass : BaseClass
#if (useInterface)
, MyInterface
#endif
{
public class MyTemplateClass : BaseClass
#if (useInterface)
, MyInterface
#endif
{
Then the outputted code would be:
public class MyTemplateClass : BaseClass
, MyInterface
{
public class MyTemplateClass : BaseClass
, MyInterface
{
Which we can all probably agree on does not look that great Is there a way to inline these conditionals? For example, something like:
public class MyTemplateClass : BaseClass #if (useInterface) , MyInterface #endif {
public class MyTemplateClass : BaseClass #if (useInterface) , MyInterface #endif {
8 Replies
ero
ero3w ago
as a possible work around, can you conditionally include entire different files?
Ruttie
RuttieOP3w ago
That is a possibility, but how would the naming of the file work not to mention the duplicated code
ero
ero3w ago
what about
#if (useInterface)
public class MyTemplateClass : BaseClass, IMyInterface
#else
public class MyTemplateClass : BaseClass
#endif
{
#if (useInterface)
public class MyTemplateClass : BaseClass, IMyInterface
#else
public class MyTemplateClass : BaseClass
#endif
{
Ruttie
RuttieOP3w ago
That is an amazing solution, I might go with that thanks :catbless:
ero
ero3w ago
👍
canton7
canton73w ago
You can also use partial classes
Ruttie
RuttieOP3w ago
I did consider that, but I feel like it'd be hell to actually work with
canton7
canton73w ago
public partial class MyTemplateClass : BaseClass
{

}

#if USE_INTERFACE
partial class MyTemplateClass : IMyInterface { }
#endif
public partial class MyTemplateClass : BaseClass
{

}

#if USE_INTERFACE
partial class MyTemplateClass : IMyInterface { }
#endif
(not that it's any prettier tbh)

Did you find this page helpful?