Reputation: 10967
Today i had a challenge with my College and i gaved up ,no idea how to achieve it . Is there a way to declare a String ,as Constant and on Load Event maybe using Reflection to change String to non-Constant assign a value from XML ,than Change it to Constant again .
And all of the Code which does that (Constant to Non-Constant),should be Stored in a String ,and on Load before Type Change ,it should be Decrypted and Injected into the Application .
example:
private const String RegNumber = "";
//Change RegNumber to Writable String
//Change RegNumber value
//Than Change RegNumber back to const again
PS : Please sorry but i have no idea where to start ,and show here some code .
Upvotes: 0
Views: 862
Reputation: 1500035
You can't declare it as const
but you can declare it as static readonly
:
private static readonly string Foo = ReadValueFromAssembly();
static string ReadValueFromAssembly()
{
// Perform your logic and return the string here
}
Would that do everything you need? It's not really clear what you mean about the "code which does that [...] should be decrypted and injected into the application" but you can make the above method do anything you need it to as normal.
As a side-note, it's generally a bad idea to do a lot of work in a type initializer like this.
EDIT: You can store code as a string, use CSharpCodeProvider
to compile it at execution time, and then execute the compiled code. I have a sample of this in "Snippy" which I used for C# in Depth as a quick tool for compiling snippets.
Upvotes: 1
Reputation: 22661
It is theoratically possible. See
How to programmatically compile code using C# compiler
http://support.microsoft.com/kb/304655
You can write the code in a string and compile using the API mentioned in above article.
I have not done that before but it should give you an idea on how to start.
Also see,
Can I change value of constant in C#?
Upvotes: 0
Reputation: 1086
It may not even exist at runtime, the compiler could have just replaced all usages of it with their literal values (in fact, it probably has, though I don't think it's required to by the standard).
So no, I don't see how this could be possible.
Upvotes: 0