Juan Carlos Oropeza Juan Carlos Oropeza - 29 days ago 11
C# Question

Static Type Mess

Static Type cant be used as type arguments

BUT

Extension Method should be in a Static class

I have a class

piece
so I can create
List<piece>
in my code

Now when I try to create an extension and ask me to create the class as static. But if I do that can't create
List<piece>
. So I'm in a recursive dilema here.

As you can see I'm trying to clone my piece.

public class piece
{
public int height { get; set; }
public int width { get; set; }
public int[] shape { get; set; }
public int quality { get; set; }
public int x { get; set; }
public int y { get; set; }

public static T CloneJson<T>(this T source)
{
// Don't serialize a null object, simply return the default for that object
if (Object.ReferenceEquals(source, null))
{
return default(T);
}

return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(source));
}
}


So what is the proper way to handle this scenario?

I have my class working fine. I try to add clone functionality and found that extension method. That is when mess start, yes, I'm not really familiar with extension or instance method. I'm trying to make it work

My guess is create the extension as a method instead, but I don't know how to do that.

Answer

Two things you need to consider:

First: that method have no reason to be on that class. It does not represent any functionality of piece, as it is generic and can return any type.

Second: Extension methods should be on static class, yeah, but not on the same class where the type is defined. It must be defined on a static class and is consumed by other classes by referencing to that static class namespace.

So what you probably want to do is something like this:

namespace MyApp.MyExtensions
{
   public static class CloneExtensions 
   {
       public static T CloneJson<T>(this T source)
       {
           if (Object.ReferenceEquals(source, null))
               return default(T);

           return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(source));
       }
   }
}

Then you could use

namespace MyApp
{
    using MyApp.Extensions;

    public class TestClass
    {
        public TestClass()
        {
            var item = new piece();
            var clone = piece.CloneJson();
        }
    }
}

That method would only make sense to be on the piece class if it was explicitly typed to clone only that piece class. In that case, it shouldn't be an extension method at all, but just an regular non-static method on that class.

Comments