0

I have a function to deserialize any type of object that I get from the Api. If there is an error, I want to return a new object of type T.

I tried to do it with return new T(), but I get the error:

'T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method

What's wrong with my code?

[SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")]
        internal static T DeserializeObject<T>(this JsonSerializer serializer, string value) 
        {
            try
            {
                using (var stringReader = new StringReader(value))
                {
                    using (var jsonTextReader = new JsonTextReader(stringReader))
                    {
                        return (T)serializer.Deserialize(jsonTextReader, typeof(T));
                    }
                }
            }

            catch {

                return GetDefault<T>(); //This line returns the error
            }  
        }


        public static T GetDefault<T>() where T : new()
        {
            if (typeof(IEnumerable).IsAssignableFrom(typeof(T)))
            {
                return new T();
            }
            return default(T);
        }
  • @Cody Gray Did you not see? He already uses the type constraint! The problem is a different one – adjan Jun 16 '17 at 11:56
  • @adjan OP is only using the type constraint in one place. The line with the error is in the method without type constraint. So it's still a duplicate. – user247702 Jun 16 '17 at 11:59
  • @Stijn but where does the other question say this is a requirement to have it in every method? – adjan Jun 16 '17 at 11:59
  • @adjan the paragraph below the first code block in the answer explains that. – user247702 Jun 16 '17 at 12:00
  • 2
    @AndersonPimentel I am aware of that. I just don't see where the duplicate answer explains that. – adjan Jun 16 '17 at 12:02
  • @Stijn Where? I don't see it? – adjan Jun 16 '17 at 12:02
  • @Cody Gray I edited the answer to something I consider a good one. I could not provide an answer myself because you have closed it for no reason. – adjan Jun 16 '17 at 12:17
  • agree with @adjan, it's actually not a duplicate and so voted to reopen – Rahul Jun 16 '17 at 12:21

1 Answers1

3

In DeserializeObject<T> you are calling

GetDefault<T>()

which has the type parameter constraint where T : new(), but DeserializeObject<T>'s T is unconstrained. You have to add the constraint to DeserializeObject<T> as well:

internal static T DeserializeObject<T>(this JsonSerializer serializer, string value) : where T : new()
adjan
  • 13,371
  • 2
  • 31
  • 48
Rahul
  • 76,197
  • 13
  • 71
  • 125