Dzmitry
Dzmitry

Reputation: 749

Convert to type declared in Class Type

folks, I have a method in i pass object of type Type. And i want to convert object that i have in this method, to type in Type. For example

void SetNewRecord(Type requiredType)
{
  var list = GridView.DataSource as requiredType;
  for (int i = 0; i < list.Length; i++)
  {
    if (list[i].KOD == kod)
    {
      GridView.CurrentCell = GridView[0, i];

      return;
    }
  }
}

if i pass int[] as parameter, i want that GirdView.DataSource be converted to int[]. Is it possible in C# ?

Upvotes: 1

Views: 164

Answers (1)

Stecya
Stecya

Reputation: 23276

You can try to use Generic to solve your problem

public interface ISample
{
    object KOD {get;set;} 
}

void SetNewRecord<T>() where T : ISample
{
     var list = GridView.DataSource as IEnumerable<T>;
     // implement needed logic here
}

And if you want to call it via reflection

 MethodInfo castMethod = this.GetType().GetMethod("SetNewRecord").MakeGenericMethod(type);
 castMethod.Invoke(null, null);

Upvotes: 1

Related Questions