Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# How to Declare unknown method types

Tags:

c#

I have to provide search functionality to end user and for that purpose i am providing a dropdown and a textbox, the dropdown has options like EmployeeID, DisplayName, City and after selecting the dropdown value he needs to enter a value in the textbox.

If the user selects EmployeeID then the value will be of type Int and if he selects Name or city the value will be of type string.

Public Employee getEmpInfo(object querystring, object queryvalue)
{
// code to get the empplyee info
}

I would like to know if there is any better approach than using object type ?

like image 710
user3198688 Avatar asked Dec 29 '25 09:12

user3198688


2 Answers

You can overload your method like this:

If your parameter is int:

public Employee getEmpInfo(int employeeId){
   // query by ID
}

Or a string

public Employee getEmpInfo(string employeeName){
    // query by name
}

Then if you give string, the second will be used by the program, else the first will be. You can both write these functions in your file. It's called method overloading.

References:

https://www.geeksforgeeks.org/c-sharp-method-overloading/

https://www.tutorialspoint.com/What-is-method-overloading-in-Chash

Function Overloading


On the other hand, if you want to use one function to search all types:

public class SearchParams {
    public int ID;
    public string Name;
    public string City;

    public SearchParams(int ID = null, string Name = null, string City = null)
    { 
         this.ID = ID;
         this.Name = Name;
         this.City = City;    
    }
}


public function getEmpInfo(SearchParams params){
    // build query by that parameters
    if(ID != null){
       // add query by ID
    }
}
like image 166
Taha Paksu Avatar answered Dec 30 '25 23:12

Taha Paksu


It is possible to solve this in the UI by adding and binding controls for all properties and depending on the selected property name in the combobox, showing only the control for selected property.

This approach makes it possible to have very specific controls for some properties instead of forcing everything to string input.

How this should be done depends on the UI technology (Web, WinForms, WPF, ...)

like image 40
Emond Avatar answered Dec 30 '25 22:12

Emond



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!