Extension Method not clear in the following program - c#-3.0

I have the following program which i found in my learning. I am not understanding the output in which why Class3 and class4 method calling differs from class1 and class2. I see no difference in all the four classes. And how come class1 and class2 calls extension method automatically?
using System;
class Class1 {
}
class Class2 {
public void Method1(string s) {
Console.WriteLine("Class2.Method1");
}
}
class Class3 {
public void Method1(object o) {
Console.WriteLine("Class3.Method1");
}
}
class Class4 {
public void Method1(int i) {
Console.WriteLine("Class4.Method1");
}
}
static class Extensions {
static public void Method1(this object o, int i) {
Console.WriteLine("Extensions.Method1");
}
static void Main() {
new Class1().Method1(12); // Extensions.Method1 is called
new Class2().Method1(12); // Extensions.Method1 is called
new Class3().Method1(12); // Class3.Method1 is called
new Class4().Method1(12); // Class4.Method1 is called
}
}
Any help appreciated pls?

I see no difference in all the four classes.
Look closer. Class1 has no native method at all. And the method signatures in the other three classes are all different. The method signature is key in the compiler determining which method is going to be called.
new Class1().Method1(12); // Extensions.Method1 is called
Class1 has no native Method1, so the only thing that can be called is the extension method.
new Class2().Method1(12); // Extensions.Method1 is called
Class2 does have a native Method1, but that method expects a string as an argument. An int is being provided, which is what the extension method expects. This resolves to the extension method the same as it would if there was no extension method and Class2 had two overloads, one with a string and one with an int.
new Class3().Method1(12); // Class3.Method1 is called
Class3 has a native method which expects an object. Since that is satisfied by the integer being supplied, it takes priority over the extension method.
new Class4().Method1(12); // Class4.Method1 is called
Same as Class3 above, there is a native method which is satisfied by this call. This one is even more specific, taking an int as an argument.

Related

(OOP) Implementing a pre-programmed function in a class

An experimental/theoretical question concerning any OOP language (Java, C#, Typescript, etc..)
Usually, when implementing an interface in a class, one has to override all the functions of that interface in the class by having to write the code for each function from that interface. And every class that implements this interface has to have its own code for those functions. Suppose we have an interface called Test that has a function called foo() in which I want the following code System.out.println("This is an interface function");.Usually one has to make an interface and declare the function and then writes the code in every implementing class
But what if there is some "theoretical" way of having all of the function written in the interface and every implementing class can just call it without having to override. Something like the following (using Java as a base language):
interface Test {
public foo() {
System.out.println("Test log.")
}
}
class Class1 implements Test {
constructor() {}
}
class Class2 implements Test {
constructor() {}
}
class Main {
public static void main() {
Class1 f1 = new Class1();
Class2 f2 = new Class2();
f1.foo();
f2.foo();
}
}
Java has this feature since Java 8. Interfaces can have default implementations where the class is free to override them, but not required to do so.
interface Test {
default void foo() {
System.out.println("Test log.");
}
}

OOP classes: Override static method in child class, depending of called method

I have the ParentClass, with method TestMethod (NOTE: I shouldn't make any changes to the ParentClass at all, it should stay as it is):
class ParentClass{
public static function TestMethod() {
return "original method";
}
}
And the child class that extends original class has two additional methods (ChildMethod1 and ChildMethod2) that are not included in the ParentClass:
class ChildClass extends ParentClass{
public function ChildMethod1() {
.
.
.
}
public function ChildMethod2() {
.
.
.
}
}
I'm instancing and working with an objects from ChildClass. But I need to override the TestMethod from the ParentClass.
In the moment when I will call the ChildMethod1, the TestMethod from the ParentClass should be overriden and to look like this:
public static function TestMethod() {
return "child method 1";
}
and in the moment when I will call the ChildMethod2, the TestMethod should be overridden like this:
public static function TestMethod() {
return "child method 2";
}
so probably the ChildClass should look like this:
class ChildClass extends ParentClass{
public function ChildMethod1() {
.
.
.
}
public function ChildMethod2() {
.
.
.
}
public function TestMethod() {
if(some condition){
return "child method 1";
} else {
return "child method 2";
}
}
}
NOTE: TestMethod in ParentClass is actually a static function.
Is there any way of implementing this logic without any change to the ParentClass? I was thinking maybe introducing the variable in ChildClass can help us in the creating the conditions in overriden class, but not sure how to implement all of that.
As far as I know, since a static method isn't part of a class instance, it can't be overridden. This is by design in every programming language in the world.
If these static methods were instance methods...
...probably you would end up implementing two derived class of ParentClass and that conditional logic would be implemented where you instantiate the so-called derived classes, and this means that you would be taking advantage of polymorphism:
ParentClass instance;
if([condition])
{
instance = new DerivedClass1();
}
else
{
instance = new DerivedClass2();
}
instance.OverriddenMethod();
}
When you cast a reference of a most derived instance into a less derived one, you're performing an upcast. While you're upcasting either DerivedClass1 or DerivedClass2, you're not losing their implementations of OverriddenMethod, because upcasting just reduces the typing without losing implementation details.

Java8 overriding (extending) default method

Suppose we have a default method in a interface,
in implementing class if we need to add some additional logic besides the one the default method already does we have to copy the whole method? is there any possibility to reuse default method... like we do with abstract class
super.method()
// then our stuff...
You can invoke it like this:
interface Test {
public default void method() {
System.out.println("Default method called");
}
}
class TestImpl implements Test {
#Override
public void method() {
Test.super.method();
// Class specific logic here.
}
}
This way, you can easily decide which interface default method to invoke, by qualifying super with the interface name:
class TestImpl implements A, B {
#Override
public void method() {
A.super.method(); // Call interface A method
B.super.method(); // Call interface B method
}
}
This is the case why super.method() won't work. As it would be ambiguous call in case the class implements multiple interfaces.

Calling Partial Methods in C#

i was recently digging on new partial methods in c#3.0, i understood the use of partial class, that it could be chunked into multiple file one contain the definition and other declaration, but i wanted to know,i created a partial class like below:
in class1.cs
partial class A
{
partial void Method();
}
in class2.cs
partial class A
{
partial void Method()
{
Console.WriteLine("Hello World");
}
}
now in class3.cs
class MainClass
{
static void Main()
{
A obj = new A();
obj.Method(); //Here i cannot call the "Method" method.
}
}
then whats the use of creating partial method, i read on MSDN that, at runtime, compiler compiles the class into one, in that case compiler should be getting the "Method" method implementation also, then why it dont allow me to call the "Method" method in the main method, can anyone correct me if i am wrong, and tell me why i am unable to call this partial method in main.
From MSDN
No access modifiers or attributes are allowed. Partial methods are
implicitly private.
It's a private method, so you can't call it from main.
You can call a partial method inside the constructor where the method is defined.
For example
public partial class classA
{
partial void mymethod();
}
public partial class classA
{
partial void mymethod()
{
Console.WriteLine("Invoking partial method");
}
public ClassA()
{
mymethod();
}
}
public class MainClass
{
static void Main()
{
ClassA ca=new ClassA();
}
}
That's it..now execute your code and see the result..
OutPut
Invoking partial method
Yes, we can't call it from Main(). Problem is not Partial method problem is method without specifier in a class is Private and private method can be called inside the class only.
Try creating a new public method in Partial class:
partial class A
{
partial void Method();
}
partial class A
{
partial void Method()
{
Console.WriteLine("Hello World");
}
public void Study()
{
Console.WriteLine("I am studying");
Method();
}
}
class MainClass
{
static void Main()
{
A obj = new A();
obj.Study();
}
}

Forcing the use of a specific overload of a method in C#

I have an overloaded generic method used to obtain the value of a property of an object of type PageData. The properties collection is implemented as a Dictionary<string, object>. The method is used to avoid the tedium of checking if the property is not null and has a value.
A common pattern is to bind a collection of PageData to a repeater. Then within the repeater each PageData is the Container.DataItem which is of type object.
I wrote the original extension method against PageData:
public static T GetPropertyValue<T>(this PageData page, string propertyName);
But when data binding, you have to cast the Container.DataItem to PageData:
<%# ((PageData)Container.DataItem).GetPropertyValue("SomeProperty") %>
I got a little itch and wondered if I couldn't overload the method to extend object, place this method in a separate namespace (so as not to pollute everything that inherits object) and only use this namespace in my aspx/ascx files where I know I've databound a collection of PageData. With this, I can then avoid the messy cast in my aspx/ascx e.g.
// The new overload
public static T GetPropertyValue<T>(this object page, string propertyName);
// and the new usage
<%# Container.DataItem.GetPropertyValue("SomeProperty") %>
Inside the object version of GetPropertyValue, I cast the page parameter to PageData
public static T GetPropertyValue<T>(this object page, string propertyName)
{
PageData data = page as PageData;
if (data != null)
{
return data.GetPropertyValue<T>(propertyName);
}
else
{
return default(T);
}
}
and then forward the call onto, what I would expect to be PageData version of GetPropertyValue, however, I'm getting a StackOverflowException as it's just re-calling the object version.
How can I get the compiler to realise that the PageData overload is a better match than the object overload?
The extension method syntax is just syntactic sugar to call static methods on objects. Just call it like you would any other regular static method (casting arguments if necessary).
i.e.,
public static T GetPropertyValue<T>(this object page, string propertyName)
{
PageData data = page as PageData;
if (data != null)
{
//will call the GetPropertyValue<T>(PageData,string) overload
return GetPropertyValue<T>(data, propertyName);
}
else
{
return default(T);
}
}
[edit]
In light of your comment, I wrote a test program to see this behavior. It looks like it does go with the most local method.
using System;
using Test.Nested;
namespace Test
{
namespace Nested
{
public static class Helper
{
public static void Method(this int num)
{
Console.WriteLine("Called method : Test.Nested.Helper.Method(int)");
}
}
}
static class Helper
{
public static void Method(this object obj)
{
Console.WriteLine("Called method : Test.Helper.Method(object)");
}
}
class Program
{
static void Main(string[] args)
{
int x = 0;
x.Method(); //calls the object overload
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
Console.WriteLine();
}
}
}
To make sure the nesting is not affecting anything, tried this also removing the object overload:
using System;
using Test.Nested;
namespace Test
{
namespace Nested
{
public static class Helper
{
public static void Method(this int num)
{
Console.WriteLine("Called method : Test.Nested.Helper.Method(int)");
}
}
}
static class Helper
{
public static void Method(this string str)
{
Console.WriteLine("Called method : Test.Helper.Method(string)");
}
}
class Program
{
static void Main(string[] args)
{
int x = 0;
x.Method(); //calls the int overload
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
Console.WriteLine();
}
}
}
Sure enough, the int overload is called.
So I think it's just that, when using the extension method syntax, the compiler looks within the current namespace first for appropriate methods (the "most local"), then other visible namespaces.
It should already be working fine. I've included a short but complete example below. I suggest you double-check your method signatures and calls, and if you're still having problems, try to come up with a similar short-but-complete program to edit into your question. I suspect you'll find the answer while coming up with the program, but at least if you don't, we should be able to reproduce it and fix it.
using System;
static class Extensions
{
public static void Foo<T>(this string x)
{
Console.WriteLine("Foo<{0}>(string)", typeof(T).Name);
}
public static void Foo<T>(this object x)
{
Console.WriteLine("Foo<{0}>(object)", typeof(T).Name);
string y = (string) x;
y.Foo<T>();
}
}
class Test
{
static void Main()
{
object s = "test";
s.Foo<int>();
}
}