0

Consider the below code:

var list = new SomeServiceType
{
    Url = "htp://www.test.com/",
    Credentials = new NetworkCredential(UserName, Password)
};

This code has been repeated many say as 10 times. So, I decided to use a common function that accepting this above code when passing different type.

I need to get the Url and Credentials as the response from newly created function.

For reference, SomeServiceType is ServiceNowType, UserName and Password are type String.

I tried with

public List<object>(....strucked here...)
{
  ...
  return ...//again strucked here....(neeed to return url and credentials)..
}

url is of type string and NetworkCredential is of c# class

Earth
  • 3,477
  • 6
  • 37
  • 78

2 Answers2

2

You can use reflection and activator to create method, as below

 public T MyMethod<T>(string url, string userName, string userPassword) {
       var myService = Activator.CreateInstance(typeof(T));
      System.Reflection.PropertyInfo URL = myService.GetType().GetProperty("Url");
      System.Reflection.PropertyInfo NetworkCred = myService.GetType().GetProperty("Credentials");
      URL.SetValue(myService, url, null);
      NetworkCred.SetValue(myService, new System.Net.NetworkCredential(userName, userPassword), null);
      return (T)myService;
   }

Call As

var list =  MyMethod<SomeServiceType>(url,userName,userPassword);
Anubrij Chandra
  • 1,592
  • 2
  • 14
  • 22
0

you can do like these in asp.net.

        public static List<SomeServiceType> MyFunction(string url, string UserName, string Password)
        {
            List<SomeServiceType> list = new List<SomeServiceType>();
            if (url != null && UserName != null && Password != null)
            {
                list = new SomeServiceType()
                {
                    Url = "htp://www.test.com/",
                    Credentials = new NetworkCredential(UserName, Password)
                };
            }
            return list;
        }
Bharat
  • 5,869
  • 4
  • 38
  • 58