Enforcing (forcing) Resource Strings

A

Alan

Is there a way in C# to have the compiler enforce that users use
Resource Strings?

Say I have a logging subsystem, and I want make sure that the only
string values that get logged come from a resource file, can I do
that?

I know I can use:

static void LogWarning(string val)
{
...
string toLog = ResourceManager.GetString(val);
}

But that is problematic: At compile time, I have no idea if val
exists.

I can also use:

static void LogWarning(string msg)
{
....
}

LogWarning(ErrorStrings.ThisIsMyError);

But nothing stops users of this log system from passing in a hardcoded
string into my LogWarning method.

Ideally I want something that is strongly typed, but can't be
overloaded with a string.

Any ideas?
 
J

Jesse Houwing

* Alan wrote, On 28-6-2007 21:56:
Is there a way in C# to have the compiler enforce that users use
Resource Strings?

Say I have a logging subsystem, and I want make sure that the only
string values that get logged come from a resource file, can I do
that?

I know I can use:

static void LogWarning(string val)
{
...
string toLog = ResourceManager.GetString(val);
}

But that is problematic: At compile time, I have no idea if val
exists.

I can also use:

static void LogWarning(string msg)
{
...
}

LogWarning(ErrorStrings.ThisIsMyError);

But nothing stops users of this log system from passing in a hardcoded
string into my LogWarning method.

Ideally I want something that is strongly typed, but can't be
overloaded with a string.

Any ideas?

There is an FxCop rule to enforce this, if you're using Visual Studio
Team System Developer or Suite you can enforce these rules before check-ins.

There is no way however to make every string parameter unsuitable for a
strings. You can make a resource file type safe in .NET 2.0. If you open
a resource file and look in the information/message tab there should be
a link there to generate a typed class for that specific resource file.

If you're still using .NET 1.1 you can use the String Resource Tool. But
I don't know where it moved to with the close down of Got Dot Net.
Here's a post about it:

http://blogs.msdn.com/scottdensmore/archive/2005/07/08/436867.aspx

I hope this helps,

Jesse
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top