Anton  Voronin
Anton Voronin

Reputation: 108

Restrict passing instances of derived classes as method parameters

Here's the situation. I have a class and a derived class

public class MyClass
{  }

public class MyDerivedClass : MyClass
{  }

And also I have a method (in an external class) which takes an instance of MyClass as a parameter:

public class AnotherClass {
  public void DoSomething(MyClass myClass) 
  { }
}

How can I restrict DoSomething method to accept instances of MyClass only, but not instances of MyDerivedClass?

Upvotes: 0

Views: 351

Answers (2)

Zinov
Zinov

Reputation: 4119

What are you trying to do here is more related to an Invariance problem that is pretty common on all programming languages.

Means that you can use only the type originally specified; so an invariant generic type parameter is neither covariant nor contravariant. You cannot assign an instance of IEnumerable (IEnumerable) to a variable of type IEnumerable or vice versa.

Here is the reference for you https://msdn.microsoft.com/en-us/library/dd799517(v=vs.110).aspx

My advice, try to change the implementation and put all the methods into an interface, that should be more clear

class Root: Interface
{
 ...implementation of your common methods
}

class Derived: Interface
{
  ...implementation of your common methods
  //this should just
  public void DoSomething(MyClass myClass)
}

If you don't want to use the above approach then use the "as" operator to treat the parameter that you are passing as MyRootClass, var a = parameter as MyRootClass. If a is null then you are not passing the correct value to the method, or check for the type directly.

If would recommend that you read this topics:

http://amapplease.blogspot.com/2009/04/invariance-covariance-contravariance.html https://stackoverflow.com/a/13107168/819153 https://blogs.msdn.microsoft.com/ericlippert/2009/03/19/representation-and-identity/

Hope this helps

Upvotes: 1

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

If that's what you want then you would need to check in code yourself that if it is a Derived type through Exception to tell the calling code that Derived type objects are not allowed for this method:

public class AnotherClass {
  public void DoSomething(MyClass myClass) 
  { 
       if(myClass.GetType() != typeof(MyClass))
       {
          throw new Exception("Derived objects not allowed");
       }
  }
}

Upvotes: 1

Related Questions