hamik qosakyan
hamik qosakyan

Reputation: 41

How to bypass function parameters in C#?

I am looking for ways to bypass function parameters. Assume i have a function:

void getDataFromDB(int? ID, string name) {....}

I would like to know the ways bypassing ID or name, smt like this:

entity.getDataFromDB(42);

or

entity.getDataFromDB("Customer");

I won't call function like this:

entity.getDataFromDB(null,"Customer");

I know i can use default values also i can use params for the last parameter. Any good ideas?

Upvotes: 0

Views: 1080

Answers (3)

Ankit Vijay
Ankit Vijay

Reputation: 4078

From what it looks like, you are looking to get data either by name or id (and not both). If that is the case, then these are two distinct operations in my mind which can be solved by method overloading like this:

void getDataFromDB(int id) { … }

void getDataFromDB(string name) { … }

If there is common code between the above two methods then you can keep the common code separate and call from each method.

Personally, I would avoid nullableparameters as we then need to put additional null checks in our method. It open doors for potential bugs.

Upvotes: 0

pm100
pm100

Reputation: 50120

combine named and optional might help.

void getDataFromDB(int? ID = null, string name = null) {....}

allows

getDataFromDB(ID:42);
getDataFromDB(name:"eric");

Upvotes: 0

adjan
adjan

Reputation: 13652

C# has two ways to reduce function parameters:

default values (works only if no "standard" parameter follows):

void getDataFromDB(int? ID, string name = "Default") {....}

Method overloads:

void getDataFromDB(int? ID, string name) {....} 
void getDataFromDB(string name) => getDataFromDB(null, name); // overload using lambda

Upvotes: 2

Related Questions