In a prism application I have a module definition like this:
[Module(ModuleName = "TestModule", OnDemand = true)]
public class Test :
ModelBase,
IModule
{
...
moduleName = "TestModule";
...
};
As you can see, these modules will be loaded at runtime and there are many of them with different module names.
In order to avoid code redundancy, I've written a base class ModelBase from which these models derive as follows:
public class ModelBase:
{
/// <summary>
/// The module name
/// </summary>
protected string moduleName;
...
}
The string moduleName is never used in ModelBase, so I get the compiler warning CS0169 which says excactly this. I don't like to suppress warnings, so I'm wondering if there is a better solution.
moduleName will be set with the actual name in the derived class as you can see in the 1st snippet.
The problem is that one cannot assign a name in the ModelBase class, since the module's name is not known here in advance.
This problem might sound stupid since one could write
public class ModelBase:
{
/// <summary>
/// The module name
/// </summary>
protected string moduleName = "";
...
}
to overcome this issue.
I wonder if there is a "best practise" for this recurring question. Many thanks
Juergen
I would personally make this an abstract property:
protected abstract string ModuleName { get; }
As an extra bonus, this will force the derived class to implement it, which should reduce the potential for errors. If your usage of the ModuleName should be public, you can of course make the property public, as well.
A similar alternative would be to make this a constructor parameter of your class:
protected ModelBase(string name)
{
this.moduleName = name;
}
This would, again, force this to be handled in each derived class as part of the constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With