Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional parameter not working correctly

I have a method which takes last parameter optionally.

public static DataTable GetQueryResult<T>(string connectionString, string queryText, Dictionary<string, T> dicParameters = null)

When I try to call this method like:

DBOperations.GetQueryResult(myConnectionString, myQuery);

It says no overload for method 'GetQueryResult' takes 2 arguments.

This documentation explains that I can pass only needed parameters to this kind of method.

Regards

like image 794
Xelom Avatar asked Feb 26 '26 20:02

Xelom


2 Answers

You must explicitly specify the T:

DBOperations.GetQueryResult<YourType>(myConnectionString, myQuery);

When you specify the dicParameters, the T is implicit:

var dicParameters = new Dictionary<string, YourType>();
DBOperations.GetQueryResult(myConnectionString, myQuery, dicParameters );
like image 106
Ed Chapel Avatar answered Mar 01 '26 09:03

Ed Chapel


In this case it is better to have an overload rather than a default parameter.

As you can see from the other answers, if you use a default parameter and the caller does not specify it, then they will need to specify the type of T in the call:

DBOperations.GetQueryResult<MyType>(myConnectionString, myQuery);

However, because the dictionary is not used if it is null (presumably!), then it is pointless for the caller to have to specify an arbitrary type just to call the function when not specifying a dictionary.

So you should introduce an overload which doesn't have the dictionary parameter at all, so the caller won't have that problem.

like image 41
Matthew Watson Avatar answered Mar 01 '26 09:03

Matthew Watson