Mohit Mohit - 2 months ago 7
C# Question

Implements Generics in C#

I am a student and want to implement generic in my test project. Below is my code

class clsCallService
{
public void CallServiceMethod(string serviceName)
{
if (serviceName == "WEB")
Web_Service.AddData("4G", DateTime.Now, DateTime.Now, "test");
else if (serviceName == "VOICE")
Voice_Service.AddData("4G", DateTime.Now, DateTime.Now, "test");
else if (serviceName == "VIDEO")
Video_Service.AddData("4G", DateTime.Now, DateTime.Now, "test");
}
}

class Web_Service
{
public static void AddData(string technology, DateTime SDate, DateTime EDate, String someVariable)
{
//Call DAL method
}
}

class Voice_Service
{
public static void AddData(string technology, DateTime SDate, DateTime EDate, String someVariable)
{
//Call DAL method
}
}

class Video_Service
{
public static void AddData(string technology, DateTime SDate, DateTime EDate, String someVariable)
{
//Call DAL method
}
}


Now, I want to create a generic class. In this class, there should be a generic method which has a generic parameter. So, I wouldn't need to write IF Condition like above. I just need to pass a object of any class and base of type, method will be called. I am trying to write some code but not able to do.

public class testGenericClass<T> where T : Web_Service, new()
{
public void CallServiceMethod(string technology, DateTime SDate, DateTime EDate, String someVariable)
{
T.AddData(technology, SDate, EDate, someVariable);
}
}


Please suggest.

Answer

Declare an interface that all your classes would implement, like

interface IService 
{
    void AddData(string technology, DateTime SDate, DateTime EDate, String someVariable); 
}

Then each class implements, like:

public class Web_Service : IService
{
    public void AddData(string technology, DateTime SDate, DateTime EDate, String someVariable) {
        // do stuff... 
    }
}
// etc...

I think it's worth pointing out that if you use an interface like this, you could just accept a parameter of type IService, not needing generics at all.

public void CallServiceMethod(IService service, string technology, DateTime SDate, DateTime EDate, String someVariable) 
{
    service.AddData(technology, SDate, EDate, someVariable); 
}

If you need something that uses a generic method for some reason, then a generic method could be written, constrained by the interface,

public class testGenericClass<T> where T : IService
{
    public void CallServiceMethod(T t, string technology, DateTime SDate, DateTime EDate, String someVariable)
    {
        t.AddData(technology, SDate, EDate, someVariable);
    }
}

Note that this method requires that the interface method AddData() is an instance method, not a static method like you have now.

Comments