I have the following classes:
// abstract
abstract class Module
{
public Options Params;
}
abstract class Options { }
// implementation
class MyModule : Module
{
public new MyOptions Params = new MyOptions();
}
class MyOptions : Options
{
public string Param1;
}
and code:
var MyMod = new MyModule();
MyMod.Params.Param1 = "new value"; // ok
// convert
Module Mod = MyMod; // if use MyModule Mod - ok
if (Mod.Params as MyOptions != null)
{
MessageBox.Show("cast OK"); // not execute
}
Modules can be of different types (I don't know them), but it is always inherited from Module. I need to determine whether the field Params is instance(or implements) MyOptions and get value, if true it. I would be happy with any decisions.
You are hiding the Options field using the new keyword, thus it would only be accessible when called from MyModule.
There is no connection between Module.Params and MyModule.Params, and even though the runtime knows that Mod is a MyModule, it still gets the value from Module.Params, which is null.
See Knowing When to Use Override and New Keywords
If you want true inheritance, you'll need to use virtual methods (or in this case, virtual properties):
abstract class Module
{
public abstract Options Params { get; set; }
}
class MyModule : Module
{
private Options myParams = new MyOptions();
public override Options Params
{
get { return myParams; }
set { myParams = value; }
}
}
var MyMod = new MyModule();
(MyMod.Params as MyOptions).Param1 = "new value";
Module Mod = MyMod;
if (Mod.Params as MyOptions != null)
{
Console.WriteLine("cast OK");
}
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