vendredi 20 août 2021

How to get generic method parameter property name in C#?

The expected result is to get the method parameter T property Name. Here is my code,

I have tried few suggested workarounds to make use of class ABC typeof(ABC).GetProperties - didn't get the expected result.

public class ABC
{
  public string Name { get; set; }
  public int RecordCount { get; set; }
  public decimal Total { get; set; }
  public DateTime CreatedDate { get; set; }
}

public void ExecuteMain()
{
  var item = new ABC
  { 
    Name = "TestUser A", 
    RecordCount = 10, 
    Total = 100.20m, 
    CreatedDate = DateTime.Now 
  };
  AddTest<string>(item.Name);
  AddTest<int>(item.RecordCount);
  AddTest<decimal>(item.Total);
  AddTest<DateTime>(item.CreatedDate);
}

private string AddTest<T>(T field)
{
  var resultName = nameof(field); // should return as "Name" 
  var resultValue = field.ToString(); // this returns "TestUser A" which is correct

  //Record Count, Total, CreatedDate  to add later
  return $"Name = {resultName}:{resultValue}";
}

Expecting result in this line

var resultName = nameof(field); // should return as "Name" 




Aucun commentaire:

Enregistrer un commentaire