Bob Bryan
Bob Bryan

Reputation: 3847

How to pass properties to a method in another namespace

I have defined some settings and plan on defining many more in my VS 2008 C# WPF project. I am aware that settings can be specified in the project through the settings designer at design time. I am also aware that the settings can be retrieved and set during run time. What I would like to do though is be able to access the settings from other assemblies and projects.

I don't understand how this can be done without writing a new class. Since the settings class is defined in my root namespace, I can't access the settings directly from other assemblies without creating a circular reference (which is what happens if you try to add a reference to a project that is already referencing that project). Is there a way to pass the properties without having to create a duplicate class with the exact same property definitions?

Upvotes: 0

Views: 2135

Answers (1)

Julián Urbano
Julián Urbano

Reputation: 8488

I understand you're trying to read properties from an assembly that you did not reference in your project. In that case, reflection is the answer.

Read the info from that assembly, wherever the dll is. Load the Settings class, get the Default settings, and access the parameter you want.

As an example, I have a dll called se2.dll, with a parameter that I'd normally access as:

string parameterValue = se2.Settings2.Default.MyParameter;

Now, from a different project, I have to use reflection like this:

// load assembly
 System.Reflection.Assembly ass = System.Reflection.Assembly.LoadFrom(@"M:\Programming\se2\se2\bin\Debug\se2.exe");
// load Settings2 class and default object
Type settingsType = ass.GetType("se2.Settings2");
System.Reflection.PropertyInfo defaultProperty = settingsType.GetProperty("Default");
object defaultObject = defaultProperty.GetValue(settingsType, null);
// invoke the MyParameter property from the default settings
System.Reflection.PropertyInfo parameterProperty = settingsType.GetProperty("MyParameter");
string parameterValue = (string)parameterProperty.GetValue(defaultObject, null);

Upvotes: 1

Related Questions