String.MemberwiseClone() method called through reflection doesn't work, why?
Asked Answered
R

1

4

Let me start by saying that I know it is a protected method and I'm not supposed to call it, but shouldn't it work since MemberwiseClone is defined in the Object class and String inherits from it?

So this is the cloning method (I removed null reference handling to focus on what's important):

public static T ShallowClone<T>(T obj)
{
    MethodInfo memberwiseClone;
    memberwiseClone = obj.GetType().GetMethod("MemberwiseClone", BindingFlags.Instance | BindingFlags.NonPublic);
    return (T)memberwiseClone.Invoke(obj, null);
}

And if I call it like this:

string str = ShallowClone("My string");

The resulting string (str) will be:

"M\0\0\0\0\0\0\0\0"

Thanks in advance!

Recourse answered 17/5, 2012 at 23:3 Comment(3)
Wild guess: the underlying native is a pointer, MemberwiseClone takes the value (i.e. the first character) and the length without copying the rest of it.Franks
What is the point of cloning a string?Pollerd
I was cloning elements from a collection and happened to find a string along the way...Recourse
E
2

You are calling it and it is working. The problem is that String.MemberwiseClone is not doing what you are expecting it to do. It appears to create a string with the same length as the original string, but only copies over the first character.

I think the lesson to be learned here is: When you call a method you're not supposed to call, be very careful, learn what it does, and don't assume too much.

Espadrille answered 17/5, 2012 at 23:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.