lss
lss

Reputation: 23

C# Dynamic IEnumerable <class>

Anyone know how to pass the IEnumerable<xxxxx> into method. XXXXX is refer to any class. I want to make it dynamic to accept any class. Example, <student>, <course>, <semester>, etc. Currently it is fixed as Employee class.

public IEnumerable<Employee> GetJsonFile(string strFolder, string strFileName)
{
      string strFile = Path.Combine(WebHostEnvironment.WebRootPath, strFolder, strFileName);
      using (var jsonFileReader = File.OpenText(strFile))
      {
        return JsonSerializer.Deserialize<Employee[]>(jsonFileReader.ReadToEnd(), new JsonSerializerOptions { PropertyNameCaseInsensitive = true});
      }
}

Upvotes: 1

Views: 59

Answers (2)

mikek3332002
mikek3332002

Reputation: 3562

Instead of using <Employee> use <T>

public IEnumerable<T> GetJsonFile<T>(string strFolder, string strFileName)
{
    ...return JsonSerializer.Deserialize<T[]>...
}

Then when you call the method you supply it with the type.

var x = GetJsonFile<student>(folder,file);

For more information lookup information on C# Generics.

Upvotes: 0

Asif
Asif

Reputation: 184

Use Generics. IEnumerable<T> Where T is a class. Generics Guide

Upvotes: 1

Related Questions