473,320 Members | 2,104 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Modify a const string via reflection/unsafe code?

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(t r) 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).

Apr 17 '07 #1
2 9966
Hi,

the difference between a const and a readonly field is, that a read only
field is a storage location wich can only be written while class resp.
instance construction.
Constant values are evaluated while compilation and so, referencing methods
are using the value, wich was there while compile time. Still this doesn't
really declare, why the manipulation doesn't work, because they still
reference the same instance. Maybe GetValueDirect wirks differently with a
constant.

But even if this would work, this still wouldn't influence the logic of
other assemblies, and it surely doesn't influence occasions where the
constant is used inside a constant expression.

Why do you want to manipulate a const in the first place. If there is any
reason to change it, than it was an error for it, to be a constant.
A constant, aswell as a readonly field is there for a reason and many
method, maybe in other assemblies may reference it. You would influence all
this methods, causing a great mess. Even reparing a bug with this very
likely would produce new bugs on other places.

hth
Christof
Apr 17 '07 #2
The reason this does not work is because the value of a constant is taken at
compile time rather than a reference to the constant. This means that nowhere
in the code will actually reference the constants value apart from the
constant definition. This means the code after compilation is exactly the
same as:

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(t r) as
string;
StringManip(value);

Console.WriteLine("Const");
Console.WriteLine(Test.ReadOnly);

value = "Const";
StringManip(value);

Console.WriteLine("Const");
}
}

This doesnt actually give the output you specify but I imagine the last
Console.writeline in your code wrote out the variable value rather than the
const.

Remember that this happens because you told the compiler that the value of
the const field will never change and therefore it is more performant (at
runtime) to not reference the value but copy it around the compiled code

HTH
--
Ciaran O''Donnell
http://wannabedeveloper.spaces.live.com
"wi******@hotmail.com" wrote:
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(t r) 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).

Apr 17 '07 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: mcdonamw | last post by:
This may sound like a stupid stupid question and I figure it would b more "general" than pertaining to a specific Language. I'm using vb.net and I have a bunch of Const values in my program. can...
8
by: Roger Leigh | last post by:
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 A lot of functions use const pointer arguments. If I have a non-const pointer, it is transparently made const when I pass it to the function, e.g....
20
by: Blah | last post by:
In MSDN documentation it states.. Remarks The constant declaration can declare multiple constants, for example: public const double x = 1.0, y = 2.0, z = 3.0; The static modifier is not...
2
by: Manish Soni | last post by:
I am loading an assembly using reflection. Then I get all the methods in all types. I want to check whether a method is "unsafe". The MethodInfo class does not seem to provide this information. ...
17
by: Chad Myers | last post by:
I've been perf testing an application of mine and I've noticed that there are a lot (and I mean A LOT -- megabytes and megabytes of 'em) System.String instances being created. I've done some...
1
by: Stabiplan BV | last post by:
Hi, I am trying to find const variables outside a class. Thur far I did not succeed. Without const, the variable is found but with const not. So, how can I get hold on global const variables...
41
by: Serve Laurijssen | last post by:
Theres a certain style of coding that uses const as much as possible. Like const int foo(const int a, const int b) { const int retval = pow(a, b); return retval; } one argument to use code...
9
by: Bill Grigg | last post by:
All, Can anyone supply an example or reference to an example of using reflection to determine the data types and array lengths contained in a nested stucture in C#? Actually, it is a structure...
6
by: chandramohanp | last post by:
Hi I am trying to modify class instance members using reflection. I am having problem when trying to add/remove/display elements related to List<int> member. Following is the code. class...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.