How to prevent shadowing and promote given method? - c#

In C++ it is done with "using", and in C#?
public class foo
{
public void print(string s) {...}
}
public class bar : foo
{
// shadowing
public void print(object o) {...}
}
How to promote foo.print, so foo.print and bar.print would be at the same "level" for compiler (for bar of course)?
Update 1
Originally I added a paragraph about common confusion between shadowing and overriding, but then I deleted it, because I thought it will be offensive to readers.
Shadowing is like overloading spanned over inheritance tree. Shadowing is NOT overriding.
Update 2
After shadowing foo.print is no longer taken into account when resolving the overloaded method print. Promoting foo.print would get it back into process -- so when I call bar_object.print("hello") the method foo.print would be called.

In your concrete example, bar.print(object) indeed "shadows" the more specific foo.print(string):
new bar().print("i am a string");
This will call the method defined on bar, although the method on foo would have a parameter that matches the type better.
What happens here is the following: The compiler finds a method on bar with the right name ("print"), the right number of parameters (1) and a parameter type to which the passed in parameter is convertable to (string can be converted to object).
Because of this, there is no reason for the compiler to look further up the inheritance chain.
As far as I am aware, there is no construct similar to C++'s using.
If you want to use the method defined on the base class, you basically have three options:
On the caller side: Convert the bar instance to foo:
var bar = new bar();
var foo = (foo)bar;
foo.print("i am a string"); // Will call foo.print(string)
On the calee side: Inside bar.print(object) check the type of the passed parameter:
public void print(object o)
{
var s = o as string;
if(s != null)
base.print(s);
else
{
// Other code.
}
}
This will come the closest to the C++ using: Actually override or hide the original method in the derived class:
public class bar : foo
{
public new void print(string s)
{
base.print(s);
}
public void print(object o)
{
// some code
}
}

Related

Why are these two methods not ambiguous?

This is the signature for the Ok() method in ApiController:
protected internal virtual OkResult Ok();
And this is my method from my RestController class (which extends from ApiController):
// Note that I'm not overriding base method
protected IHttpActionResult Ok(string message = null);
Since OkResult implements IHttpActionResult, both of these methods can be called like this:
IHttpActionResult result = Ok();
In fact, that's what I'm doing in my application.
My class PersistenceRestController (which extends from RestController), has these lines of code:
protected override async Task<IHttpActionResult> Delete(Key id)
{
bool deleted = //... Attempts to delete entity
if(deleted) return Ok();
else return NotFound();
}
This compiles fine, and no warning is raised about method ambiguity. Why is that?
PersistenceRestController has also inherited the protected methods from ApiController so it should have both versions of Ok() (and it does).
At execution, the method executed is the one from my RestController.
How does the compiler know which method to run?
Jon Skeet answered a similar question (without the inheritance complication) here:
When the compiler has two otherwise-equal options to choose from, it will use an overload which doesn't need use any unsupplied optional parameters in preference to one that does...
In your case, however, the method from the RestController is being chosen because it's the more derived class. Jon does a good job of addressing the topic in detail in his book C# in Depth -- look at the inheritance section of that page, which essentially states that the compiler will prefer a method on the actual instance class before methods on less derived classes.
EDIT:
I am leaving my original answer for posterity because I think it lets you visualize things, but DO NOT BE CONFUSED! The compiler does not actually treat the optional parameter as syntactic sugar for an overridden method. It treats it as a single method with an optional parameter. Dusty's answer, mentioning that "the method from the RestController is being chosen because it's the more derived class," is correct.
ORIGINAL (With visible edits for correctness):
Because they are NOT ambiguous. In order to be ambiguous the methods need to have the same signature. The fact that the string message parameter has a default value of null effectively creates BEHAVES as though it creates two callable overrides, one of which HIDES the original method, and one of which is distinctly callable with a string.
You are effectively doing creating the same behavior as if you were to do this:
public class RestController : ApiController
{
protected new OkResult Ok()
{
return Ok(null);
}
protected OkResult Ok(string message)
{
// Do your thing...
}
}
You will find there is no way to directly call ApiController.Ok() from PersistenceRestController.
If you want to call ApiController.Ok() from RestController, you'll have to use the base keywoard: base.Ok();
While #DimitarTsonev and #Dusty are telling true stuffs, but your answer is something between their answers. Here, you have inheritance situation. See these classes:
public class Foo {
public void Bar() {
}
}
public class Foo2 : Foo{
public void Bar(string message = null) {
}
}
public class Foo3 : Foo2{
public void Test(){
Bar();
}
}
When you call Bar() in your Foo3 class, the runtime will lookup after the method inside the Foo3 class. If found it, execute it, otherwise go to the top class: Foo2 and look after Bar method. Is there any? yes! so execute it! that's why when you call Ok, your RestControllers' version get executed.
But also, the Foo2.Bar(string message = null) will not conflict with Foo.Bar() because they are NOT ambiguous as #DimitarTsonev said. So, your code will work just fine.
AND, what about calling Foo.Bar() from Foo3? You have to use casting here:
public class Foo3 : Foo2 {
public void Test() {
Bar(); // this will execute Foo2.Bar()
}
public void Test2() {
((Foo)this).Bar(); // this one will execute Foo.Bar()
}
}
public class Foo
{
public void Bar()
{
}
public void Bar(string message = null)
{
}
}
Those are two different methods because the second has the optional argument.
However, please note that the second method called with no arguments will actually execute the first one, which may produce some unexpected behaviour.

What is Interface Duck Typing?

I heard the word Interface Duck Typing, but do not understand at all what is it? So I read a wiki about this and they said:
In computer programming with object-oriented programming languages, duck typing is a style of typing in which an object's methods and properties determine the valid semantics, rather than its inheritance from a particular class or implementation of an explicit interface. The name of the concept refers to the duck test.
But still could not understand what it. So I saw their program but they use dynamic keyword to call quack() & feather() function of all the classes.
I would request you all please explain in easy way what is Interface Duck Typing and how to implement in C# v2.0 because there is no dynamic keyword.
using System;
namespace DuckTyping
{
public class Duck
{
public void Quack()
{
Console.WriteLine("Quaaaaaack!");
}
public void Feathers()
{
Console.WriteLine("The duck has white and gray feathers.");
}
}
public class Person
{
public void Quack()
{
Console.WriteLine("The person imitates a duck.");
}
public void Feathers()
{
Console.WriteLine("The person takes a feather from the ground and shows it.");
}
}
internal class Program
{
private static void InTheForest(dynamic duck)
{
duck.Quack();
duck.Feathers();
}
private static void Game()
{
Duck donald = new Duck();
Person john = new Person();
InTheForest(donald);
InTheForest(john);
}
private static void Main()
{
Game();
}
}
}
C# has a nominal type system, so the compatibility of types is done based on their names. In your example you have two classes with a Quack method, however there is no way to write a method which can take instances of these two classes and invoke their Quack method.
In C# 2, the solution would be to introduce an interface and have both classes implement it:
public interface IQuack
{
void Quack();
}
public class Duck : IQuack { }
public class Human : IQuack { }
now you can create a method which take an IQuack instance and can call Human.Quack and Duck.Quack through it. In C#, methods are resolved 'early' at compile time, so you need to create a named type which supports the operations the method need so the compilation can succeed. Note there is still a runtime element to calling these methods, since the real implementation of IQuack.Quack needs to be resolved at runtime depending on the real type of the argument.
In a duck-typing system, no attempt is made to validate that a method exists before runtime. All that is required is that a given object supports the operation in that it has the right name and takes the required number of parameters (none in this case), hence the 'if it quacks like a duck' expression.
Duck typing in C# 2 can only be done using reflection, in this case you would accept an object argument and look for the required methods yourself:
public static void MakeQuack(object duck)
{
MethodInfo quackMethod = duck.GetType().GetMethod("Quack", Type.EmptyTypes, null);
if (quackMethod!=null)
{
quackMethod.Invoke(duck, new object[] { });
}
else
{
throw new ArgumentException("No Quack() method found on target");
}
}
C#4 makes this much simpler with dynamic:
public static void MakeQuack(dynamic duck)
{
duck.Quack();
}
It would say it is a way of coding where the you tell the compiler:
"Hey trust me I know what methods and properties this object supports. You don't need to check them for me whilst I code."
Once you run your app the compiler will go:
"Ok lets see if I could trust you. Let me do some runtime binding."
If you then made a mistake, such as using an unsupported method, the compiler will shout: "Hey man, this is not supported! Check my RuntimeBinderException!"
Duck typing allows an object to be passed in to a method that expects
a certain type even if it doesn’t inherit from that type. All it has
to do is support the methods and properties of the expected type in
use by the method. I emphasize that last phrase for a reason. Suppose
we have a method that takes in a duck instance, and another method
that takes in a rabbit instance. In a dynamically typed language that
supports duck typing, I can pass in my object to the first method as
long as my object supports the methods and properties of duck in use
by that method. Likewise, I can pass my object into the second method
as long as it supports the methods and properties of rabbit called by
the second method. Is my object a duck or is it a rabbit? Like the
above image, it’s neither and it’s both. In many (if not most) dynamic
languages, my object does not have to support all methods and
properties of duck to be passed into a method that expects a duck.
Same goes for a method that expects a rabbit.It only needs to support
the methods and properties of the expected type that are actually
called by the method.
Please refer this to get an idea about Duck Typing
http://haacked.com/archive/2007/08/19/why-duck-typing-matters-to-c-developers.aspx/
About Duck Typing:
We don't need to know what the object is, but we just want to let the
object do something if it can do.
Example:
Example, if here are the things that we want the following objects do.
PleaseWalk(new Dog());
PleaseRun(new Duck());
PleaseWalk(new Cup());
PleaseFly(new Man());
PleaseFly(new Bird());
And, here is the result after we request the above objects do the things.
So, we don't need to check what the object is, but we can let it do something enough. Here is the code that I have written in C#.
private void PleaseWalk(object obj)
{
string Method = "Walk";
MethodInfo walkMethod = obj.GetType().GetMethod(Method, Type.EmptyTypes, null);
if (walkMethod != null)
{
walkMethod.Invoke(obj, new object[] { });
}
else
{
Console.WriteLine(string.Format("I can not {0} because {1}", Method, WhoAreYou(obj)));
}
}
private string WhoAreYou(object unknown)
{
MethodInfo whoAreYou = unknown.GetType().GetMethod("WhoAreYou", Type.EmptyTypes, null);
return whoAreYou.Invoke(unknown, new object[] { }).ToString();
}
You can use Events and exploit C# best suitable overload functions.
Hopefully, it will be useful :)
To get something Like a duck typing (.Net 4.+):
using System.Collections;
using System.Collections.Generic;
public interface IAny
{
void InvokeGetterEvent();
}
public class AnyValueTypeDuck<T, V> : IAny
where V : AnyValueTypeDuck<T, V>
{
public static event System.Action<V> GetterEvent;
public T Data;
public void InvokeGetterEvent()
{
GetterEvent.Invoke((V)this);
}
}
// Then create some concrete classes:
// Example :
public class LifeConcreteProperty : AnyValueTypeDuck<int, LifeConcreteProperty>
{
}
public class ManaConcreteProperty : AnyValueTypeDuck<float, ManaConcreteProperty>
{
}
// Now to finally use it :
public class UserClass
{
List<IAny> allDuckTypes = new List<IAny>();
public void GetDucketTypeClass(IAny anyDuckObject)
{
LifeConcreteProperty.GetterEvent += GetDucketType;
ManaConcreteProperty.GetterEvent += GetDucketType;
anyDuckObject.InvokeGetterEvent();
// it will propagate to event and will invoke
// best suitable overload method (GetDucketType)
LifeConcreteProperty.GetterEvent -= GetDucketType;
ManaConcreteProperty.GetterEvent -= GetDucketType;
}
public void GetDucketType(LifeConcreteProperty originalClass)
{
// Your efforts go here
int value = originalClass.Data;
}
public void GetDucketType(ManaConcreteProperty originalClass)
{
// Your efforts go here
float value = originalClass.Data;
}
}

What method will be called if I call the inherited overload?

Lets say I have this:
class A { }
class B : A { }
class C : B { }
class Foo
{
public void Bar(A target) { /* Some code. */ }
}
class AdvancedFoo : Foo
{
public void Bar(B target)
{
base.Bar(target);
// Some code.
}
}
sealed class SuperiorFoo : AdvancedFoo
{
public void Bar(C target)
{
base.Bar(target);
// Some code.
}
}
Which overload will be called if I run new SuperiorFoo().Bar(new C()) and why?
I'm guessing it will be called cascadely but I can't figure out why and if that behavior is guaranteed.
UPDATED
So, the base. works with both Foo and AdvancedFoo for SuperiorFoo, so which one will be called and why?
Edited my answer now that the question has been revised.
A quick trace shows the following:
Entering SuperiorFoo.Bar()
Entering AdvancedFoo.Bar()
Entering Foo.Bar()
Leaving Foo.Bar()
Leaving AdvancedFoo.Bar()
Leaving SuperiorFoo.Bar()
Lets talk through what happens:
SuperiorFoo.Bar() calls its base method. Since SF.Bar() inherits
from AdvancedFoo, its base method is AdvancedFoo.Bar().
AdvancedFoo.Bar() then calls its base, which is Foo.Bar() since
AdvancedFoo inherits from Foo().
The process flow does NOT jump from SF.Bar() to Foo.Bar() because you could potentially want behaviour from the intermediate class.
If we remove the method from AdvancedFoo, the traversal is slightly different. SuperFoo.Bar() will still call its base method, but since AdvancedFoo doesn't hide the Foo.Bar() method anymore, the logic will jump to the Foo.Bar() method.
It wil keep calling the Bar() method inside SuperiorFoo untill it crashes with a StackOverflowException. If you want to call the base method of Bar() (so the method inside AdvancedFoo), you'll need to use this:
base.Bar(target);
Edit:
Looks like the code in the original post was changed. What happens now is that SuperiorFoo's 'Bar' will call AdvancedFoo's 'Bar', which will call Foo's 'Bar', and after that the code will be terminated.
Although KingCronus basically pointed out you have an infinite loop. The Signature will try to first match based on the exact type of object to the appropriate method, then should go down from that...
class Foo
{
public void Bar(A target) { /* Some code. */ }
}
class AdvancedFoo : Foo
{
public void Bar(B target)
{
base.Bar( (A)target );
// continue with any other "B" based stuff
}
}
sealed class SuperiorFoo : AdvancedFoo
{
public void Bar(C target)
{
base.Bar( (B)target );
// continue with any other "C" based stuff
}
}
By typecasting to the "Other" type (ie: B or A), it will go up to the appropriate chain...

C# - Call Method in Base Class

I have 2 classes:
public class A
{
public void WriteLine(string toWrite) { Console.WriteLine(toWrite); }
}
public class B : A
{
public new void WriteLine(string toWrite) { Console.WriteLine(toWrite + " from B"); }
}
In my code I do the following:
B writeClass = new B();
writeClass.WriteLine("Output"); // I expect to see 'Output from B'
A otherClass = (A)writeClass;
otherClass.WriteLine("Output"); // I expect to see just 'Output'
I presumed this would work because of polymorphism.
However, it always writes 'Output from B' every time. Is there anyway to get this to work the way I want it to?
EDIT Fixing code example.
When you "hide" a method from the base class using NEW you are just hiding it, thats it. It's still called when you explicitily call the base class implementation.
A doesnt contain WriteLine so you need to fix that. When I fixed it I got
Output from B
Output
namespace ConsoleApplication11
{
class Program
{
static void Main(string[] args)
{
B writeClass = new B();
writeClass.WriteLine("Output"); // I expect to see 'Output from B'
A otherClass = (A)writeClass;
otherClass.WriteLine("Output"); // I expect to see just 'Output'
Console.ReadKey();
}
}
public class A
{
public void WriteLine(string toWrite) { Console.WriteLine(toWrite); }
}
public class B : A
{
public new void WriteLine(string toWrite) { Console.WriteLine(toWrite + " from B"); }
}
}
Your method on class A is Write, not WriteLine. Change it to the same name and it will work as you expect. I just tried it and get:
Output from B
Output
Polymorphism (C# Programming Guide) explains this quite well. (This is the newer version of the original poster's link.) The page shows examples where a derived class overrides a virtual member and where new members hide base class members.
There appears to be some confusion over the new modifier. From the documentation:
Although you can hide members without the use of the new modifier, the
result is a warning. If you use new to explicitly hide a member, it
suppresses this warning and documents the fact that the derived
version is intended as a replacement.
Note that the hidden member does not need to be virtual.
Best practices:
Strongly prefer overriding to hiding. Polymorphic calls are idiomatic in OO languages.
If you intend to hide a member, always use the new modifier.
Never release code with compiler warnings.
If every developer on your team agrees that a compiler warning cannot be fixed, suppress it.
Don't use new keyword when you override the method in class B. And declare the method in A as virtual.
The 'new' keyword is making B's implementation of WriteLine overwrite A's implementation.
Don't accept this as an answer, but in my experience, it's almost always a mistake to use the 'new' keyword in this fashion. It's less readable and muddy's the clarity of your code.
Your class A has a Write function instead of WriteLine
public class A
{
public virtual void WriteLine(string toWrite) { Console.WriteLine(toWrite); }
}
public class B : A
{
public override void WriteLine(string toWrite) { Console.WriteLine(toWrite + " from B"); }
}
First: I guess you wanted to name the methods both "WriteLine" but the one in class A is only named "Write". And second: yes you inherit B from A but the object will still be of type "B" so now I don't think what you want is possible.

How to return value from C# partial method?

Is there a way to do so as it seems partial method must return void (I really don't understand this limitation but let it be) ?
Well, technically you can "return" a value from a partial method, but it has to be through a ref argument, so it's quite awkward:
partial void Foo(ref int result);
partial void Foo(ref int result)
{
result = 42;
}
public void Test()
{
int i = 0;
Foo(ref i);
// 'i' is 42.
}
In that example, the value of i won't change if Foo() is not implemented.
From MSDN:
Partial method declarations must begin with the contextual keyword partial and the method must return void.
Partial methods can have ref but not out parameters.
So the answer is no, you can't.
Perhaps if you explain a bit more about your situation (why you need to return a value, why the class is partial), we can provide a workaround.
You cannot return a value from a partial method.
Partial methods may or may not be implemented. If it were permitted to return a value from such a method, then what would the caller receive?
The reason for the restriction is this line from MSDN:
A partial class or struct may contain
a partial method. One part of the
class contains the signature of the
method. An optional implementation may
be defined in the same part or another
part. If the implementation is not
supplied, then the method and all
calls to the method are removed at
compile time. -- Emphasis Mine
If the method may not be implemented and can be removed. What would happen to its return value if the call is removed?
As to your question of a work around, that depends on what you are trying to do, but obviously you can't use a partial method.
Oh. Once I had to do this in a project of mine.
You can throw an exception in your method called ReturnValueException which you define as an exception that has an object property named ReturnedValue. Now you can call your method Foo() inside a try block and collect the results in the catch block.
No.. just kidding.
Don't do that. Ever.
Here's a technique relying on the fact that an extension method will be shadowed by a class method.
It's more involved and less clear than the ref parameter technique, so I'll use that instead.
Several shadowing mechanisms in C# could be used instead: using static vs. method, a parent class containing just the default behaviour vs. a new method, a method accepting a dummy object vs. a method with a more specific argument type etc.
The choice between the extension method or the class method when it is present is made at compile-time (that is, it doesn't use late binding). This can lead to some problems if your partial class is not sealed: if you override the customizable method with an implementation which is also customizable, you need to use a fresh interface and extension method
https://repl.it/#suzannesoy/WorthwhileSplendidBotany#main.cs
// On the auto-generated side:
interface IDefaultFoo { int DefaultFoo(); }
static class DefaultFoo {
public static int CustomFoo(this IDefaultFoo o) => o.DefaultFoo();
}
partial class PartialClass : IDefaultFoo {
int IDefaultFoo.DefaultFoo() => 42;
// mark as virtual if you want to override in subclasses too.
public virtual int Foo() => this.CustomFoo();
}
// On the user side:
partial class PartialClass {
// Define this method only if you want to change
// the default implementation of Foo.
public int CustomFoo() => 123;
}
// In subclasses use override on the Foo method as usual
class SubClass1 : PartialClass {
public new int CustomFoo() => 666; // This is not used
public override int Foo() => 999; // Use this instead
}
// If you also want to override in the subclass with a method which
// is also customizable, i.e. to provide a new default behaviour in
// the partial subclass that could also be customized, you'll need
// to add a new interface etc. otherwise the CustomFoo from the
// parent class would be called because it still shadows the
// extension method.
interface IDefaultFooSub2 { int DefaultFoo(); }
static class DefaultFooSub2 {
public static int CustomFooSub2(this IDefaultFooSub2 o) => o.DefaultFoo();
}
partial class SubClass2 : PartialClass, IDefaultFooSub2 {
int IDefaultFooSub2.DefaultFoo() => 1000000;
public override int Foo() => this.CustomFooSub2();
}
class MainClass {
public static void Main (string[] args) {
System.Console.WriteLine(new PartialClass().Foo()); // 123
System.Console.WriteLine(new SubClass1().Foo()); // 999
System.Console.WriteLine(new SubClass2().Foo()); // 1000000
System.Console.WriteLine(((PartialClass)new SubClass2()).Foo()); // 1000000
}
}

Categories