Optional parameters and inheritance

I understand the advanced options, and I really like them, but I would like to know a little about using them with a legacy interface.

Illustration A

interface IMyInterface { string Get(); string Get(string str); } class MyClass : IMyInterface { public string Get(string str = null) { return str; } } 

Now I would have thought that the Get method in MyClass inherits both interface methods, but ...

"MyClass" does not implement the interface element "MyInterface.Get ()"

Is there a good reason for this?

Perhaps I should go for it by adding additional parameters to the interface you are talking about? But what about this?

Illustration B

 interface IMyInterface { string Get(string str= "Default"); } class MyClass : IMyInterface { public string Get(string str = "A different string!") { return str; } } 

And this code compiles fine. But that can't be true? Then, with a little work, I found this:

  IMyInterface obj = new MyClass(); Console.WriteLine(obj.Get()); // writes "Default" MyClass cls = new MyClass(); Console.WriteLine(cls.Get()); // writes "A different string!" 

It would seem that the calling code receives the value of an optional parameter based on the declared type of objects, and then passes it to the method. It seems a little silly to me. Perhaps the additional parameters and method overloads have their own scripts, when should they be used?

My question

My calling code is passed an instance of IMyInterface and he needs to call both methods here at different points.

Will I be forced to implement the same method overload in every implementation?

 public string Get() { return Get("Default"); } 
+6
source share
1 answer

I also did not understand that the optional parameters do not change the signature of the method . Thus, the following code is completely legal and is actually my solution:

 interface IMyInterface { string Get(string str = "Default"); } class MyClass : IMyInterface { public string Get(string str) { return str; } } 

So, if I have an instance of MyClass , I have to call Get(string str) , but if this instance was declared as the base IMyInterface interface, I can still call Get() , which gets the default value from IMyInterface , then calls the method.

+1
source

Source: https://habr.com/ru/post/901296/


All Articles