Kevin Boss
Kevin Boss

Reputation: 145

Add an optional parameter to every method in class which inherits from base class C#

I don't know if this is possible in any way but what I try to get is to force developers who inherit from some base class to implement a specific parameter in every method in this class.

Something like:

class SomeClass : BaseClass
{
     public void SomeMethod(bool iAmAForcedParameter = false)
     {

     }
}

The reason for this is that we have services which can be called from the MVC Project (which is our frontend) or can be consumed from other services. If the service will be called from the frontend it should write the changes to the database after everything has been done. If the service gets used from another service it should only make the changes (in memory) and NOT write them to the database.

Another idea I head is to determine who is the caller and if he is from a specific type the method should not send the data. How ever, I don't know how to do this or if this is even possible without huge performance impacts.

Greetings and thanks for your help in advance.

Upvotes: 1

Views: 252

Answers (3)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236268

Its strange that each of your methods has two responsibilities. I'd rather created two derived classes. One with methods which persist data to database, and other, which don't:

class SomeInMemoryClass : BaseClass
{
   public override void SomeMethod() {}
}

class SomeSqlClass : BaseClass
{
   public override void SomeMethod() {}
}

Anyway - passing boolean to method is a design smell. It tells that your method does two things. Better to have two methods, which tell caller what they are doing:

void SomeInMemoryMethod()
void SomeSqlMethod()

Don't you think it's more maintainable, than

void SomeMethod(false)

For your last edit: Pass SomeInMemoryClass object to type which should not save data to database. Other types should use SomeSqlClass instances.

Upvotes: 1

Michel Keijzers
Michel Keijzers

Reputation: 15367

I also don't understand the second part.

For the first item, just use

public void SomeMethod(bool iAmAForcedParameter)

So without the optional argument.

In case you want to have the optional argument anyway use

public void SomeMethod(bool iAmAForcedParameter)
{
    SomeMethodX(iAmAForcedParameter)
}

public void SomeMethodX((bool iAmAForcedParameter = false)

Upvotes: 0

CodeCaster
CodeCaster

Reputation: 151654

implement a specific parameter in every method in this class.

I think you're just looking for a property on the class, which you then can check in every method.

Upvotes: 1

Related Questions