I have a generic method that takes T, GetResult<T>()
T represents many objects which have custom attribute [JsonProperty(Required = Required.Always)]
on most of their properties. Within GetResult<T>()
, I need to change T's properties to [JsonProperty(Required = Required.Default)]
and I need the next method which is called from within GetResult to get the modified version of T.
Is that possible? If so, what adjustments would I need to my sample program below?
namespace StackOverflow1
{
using System;
using Newtonsoft.Json;
class Program
{
static void Main(string[] args)
{
GetResult<Person>();
Console.Read();
}
private static T GetResult<T>() where T : Base
{
// Entering this method, T is passed with Name property set to [Required = Required.Always]
// I'm changing T's Name property to [Required = Required.Default]
var properties = typeof(T).GetProperties();
foreach (var property in properties)
{
var customAttributes = property.GetCustomAttributes(true);
foreach (var attribute in customAttributes)
{
if (attribute.GetType().Name == nameof(JsonPropertyAttribute))
{
Console.WriteLine($"Original: {((JsonPropertyAttribute)attribute).Required}");
// this is the change! But it looks like this does not actually change T which I need to forward into BuildSingleResult<T>
((JsonPropertyAttribute)attribute).Required = Required.Default;
Console.WriteLine($"After modification: {((JsonPropertyAttribute)attribute).Required}");
}
}
}
// I need T to be the **modified version** which would have [Required = Required.Default]
return BuildSingleResult<T>();
}
private static T BuildSingleResult<T>() where T : Base
{
// **** this is just to write out JsonPropertyAttribute ***
var props = typeof(T).GetProperties();
foreach (var p in props)
{
var customAttributes = p.GetCustomAttributes(true);
foreach (var attr in customAttributes)
{
if (attr.GetType().Name == nameof(JsonPropertyAttribute))
{
// This shows that T still has [Required = Required.Always] but I need it to have [Required = Required.Default]
Console.WriteLine($"(expecting Default): {((JsonPropertyAttribute)attr).Required}");
}
}
}
// *** end of debug ***
return new Person { Name = "X" } as T;
}
}
class Base
{
[JsonProperty(Required = Required.Always)]
public string Name { get; set; }
}
// This is just to demonstrate using a generic type!
class Person : Base { }
}