How to replace Marshal.SizeOf (Object) with Marshal.SizeOf <T> ()?
I create a universal class library from existing code, and I get warnings about the compiler, which for life I can not understand what to do with them.
I have a code like this:
void SomeMethod(Object data) { var size = Marshal.SizeOf(data); ... } The code builds, but in the Universal project (and, I think, .NET 4.5.1 and higher) I get the following compiler warning:
warning CS0618: "System.Runtime.InteropServices.Marshal.SizeOf (object)" is deprecated: "SizeOf (Object) may not be available in future versions. Use SizeOf <T> () instead.
But how to create a replacement for Marshal.SizeOf(Object) in the above case, using the general method without parameters Marshal.SizeOf<T>() ? Theoretically, I may not know what type of data ?
Is it because using Marshal.SizeOf(Object) is considered bad practice that it was attributed to Obsolete ? And the message really should be "completely reorganize the code"?
Well, after receiving your comments, it seems that all you need is already there:
SizeOf<T>(T) : I think this is the method you need, but you donβt need to explicitly define the general parameter due to type input . You just write var size = Marshal.SizeOf(myStructure); , and the compiler will extract this type from the given object and populate the general parameter.
SizeOf<T>() : This method comes in handy when your own class may already be a common class, and you have T , but there is no real instance of the generic type used. In this case, this method should be chosen.
How about this approach:
private static int MySizeOf(object structure) { var marshalType = typeof(Marshal); var genericSizeOfMethod = marshalType.GetMethod("SizeOf", Type.EmptyTypes); var sizeOfMethod = genericSizeOfMethod.MakeGenericMethod(structure.GetType()); var size = (int)sizeOfMethod.Invoke(null, null); return size; } Strike>