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!
MemberwiseClone
takes the value (i.e. the first character) and the length without copying the rest of it. – Franks