W
wizofaus
Given the following code:
public class Test
{
static unsafe void StringManip(string data)
{
fixed (char* ps = data)
ps[0] = '$';
}
public const string Const = "Const";
public static readonly string ReadOnly = "ReadOnly";
static void Main(string[] args)
{
string value;
TypedReference tr = new TypedReference();
value = typeof(Test).GetField("Const").GetValueDirect(tr) as
string;
StringManip(value);
value = typeof(Test).GetField("ReadOnly").GetValueDirect(tr) as
string;
StringManip(value);
Console.WriteLine(Test.Const);
Console.WriteLine(Test.ReadOnly);
value = Test.Const;
StringManip(value);
Console.WriteLine(Test.Const);
}
}
I get the output
Const
$eadOnly
$onst
That is - a const string can only be manipulated with unsafe code
*directly*, and not via reflection, whereas a static readonly string
can be manipulated with unsafe code via reflection. Obviously none of
these practices would be normal or recommended, but if I did need to
modify a const string via reflection, I don't suppose there's any way
it might be possible? (I'm trying to do this to work my way around a
bug inside .NET).
public class Test
{
static unsafe void StringManip(string data)
{
fixed (char* ps = data)
ps[0] = '$';
}
public const string Const = "Const";
public static readonly string ReadOnly = "ReadOnly";
static void Main(string[] args)
{
string value;
TypedReference tr = new TypedReference();
value = typeof(Test).GetField("Const").GetValueDirect(tr) as
string;
StringManip(value);
value = typeof(Test).GetField("ReadOnly").GetValueDirect(tr) as
string;
StringManip(value);
Console.WriteLine(Test.Const);
Console.WriteLine(Test.ReadOnly);
value = Test.Const;
StringManip(value);
Console.WriteLine(Test.Const);
}
}
I get the output
Const
$eadOnly
$onst
That is - a const string can only be manipulated with unsafe code
*directly*, and not via reflection, whereas a static readonly string
can be manipulated with unsafe code via reflection. Obviously none of
these practices would be normal or recommended, but if I did need to
modify a const string via reflection, I don't suppose there's any way
it might be possible? (I'm trying to do this to work my way around a
bug inside .NET).