Husky
Husky

Reputation: 542

How to create a dynamic type in children class, and assign it?

At first, I have a parent class like:

public class Father {
  // skip ...
}

And these are two classes that inherit from Father. But Method_A only belongs to Child_A instead of Child_B.

public class Child_A : Father {
  // skip ...

  public void Method_A { ... }
}


public class Child_B : Father {
  // skip ...
}

Finally, I try to create a variable can be assigned dynamically to

public class MyClass {
  public Father dynamicObject;

  public void MyMethod {
    dynamicObject = new Child_A(); // Sometimes will be `Child_B`.

    if (...) {                     // only `Child_A` can pass, I promise
      dynamicObject.Method_A();    // Error here.
    }
  }

The error like below:

Type 'Father' does not contain a definition for 'Method_A' and no extension method 'Method_A' of type 'Father' could be found. Are you missing an assembly reference?


I had tried var type for dynamicObject, but we must set the var type in local scope.

public class MyClass {
  public var dynamicObject; // It's not allow.
  // ...
}

Upvotes: 4

Views: 112

Answers (3)

wake-0
wake-0

Reputation: 3968

Use a cast to check the type of the dynamicObject:

Child_A childA = dynamicObject as Child_A;
if (childA != null) 
{               
    childA.Method_A(); 
}

or with C# 6 and Null-conditional operator:

Child_A childA = dynamicObject as Child_A;             
childA?.Method_A(); 

also is with an explicit (Child_A) cast could be used but I prefer the first approach.

if (dynamicObject is Child_A) {
   ((Child_A)dynamicObject).Method_A();
}

with C#7 and Pattern Matching like @Zbigniew suggested:

if (dynamicObject is Child_A child) {
   child.Method_A();
}

Upvotes: 3

levent
levent

Reputation: 3634

i thing, It makes more sense to use the Method_A over the interface. while number of methods and classes increases, it will be easier to manage

    public class Father { }
    public class Child_A : Father, IMethodOwner { public void Method_A() { }}
    public class Child_B : Father{ }
    public interface IMethodOwner { void Method_A(); }
    public class MyClass
    {
        public Father dynamicObject;
        public void MyMethod() {
            var obj = dynamicObject as IMethodOwner;
            if(obj != null)
                obj.Method_A();
        }
    }

Upvotes: 0

Aboc
Aboc

Reputation: 237

Try to replace

dynamicObject.Method_A();

by

((Child_A)dynamicObject).Method_A();

Upvotes: 0

Related Questions