How to override a function without redefine in c#? - c#

I have a requirement where I have a class and a function
public class BaseClass
{
public virtual int MyMethod(int n)
{
Console.WriteLine("BaseClass=" + n + "+" + 2);
return n + 2;
}
}
and a derived class b
where I am extending the base class function
public class A : BaseClass
{
public override int MyMethod(int n)
{
Console.WriteLine("Class A=" + n+"*"+2);
return n*2;
}
}
In the derived class when I call the function A.MyMethod()
the base function should be executed followed by the derived class function.
static void Main(string[] args)
{
A classA = new A();
A.MyMethod(1);
Console.ReadKey();
}
Is it possible?

You mean you want to call the base constructor from the derived constructor? Yes, you can do that with the base() construct.
public Derived(int sides)
: base(sides)
When Square() actually isn't a constructor (it is in your question, no return type or void) but a method, you can do it like this:
public override returntype Foo(...)
{
// your adaptation
base.Foo(...)
The method in the base class has to be virtual for this to work.

class b: a
{
public new int Square(int n)
{
var baseResult = base.Square(n);
var i = 0//extenting the code
return i;
}
}

Related

Extension for arbitrary vectors

Assume we have some structs (or classes):
public struct X
{
//...
public static X Add(X a, X b)
{
//...
}
}
public struct Y
{
//...
public static Y Add(Y a, Y b)
{
//...
}
}
Is it possible to create somewhere somehow a single method like:
public static T AddTwo(T a, T b)
{
return Add(Add(a, b), b);
}
where T can be X, Y or others and T must be the same throughout a call to such method?
Preferably without casts all the way down.
On solutions that i tried:
Generics:
A simple mechanism like:
public static class AbstractVectorProcessor<T>
{
public static T Add(T a, T b)
{
return T.Add(a, b);
}
}
is impossible to my knowledge as there is no way to tell this class that T implements T Add(T a, T b).
Interfaces:
If you implement an interface like
interface I
{
I Add(I a, I b);
}
//...
public struct X : I
//...
public struct Y : I
//...
then the result of "X.Add(new X(), new X())" will be of type I and not X. Moreover there is no problem with calling "X.Add(new Y(), new Y())".
I'm not sure what your end goal is, but I think this will point you in the right direction possibly.
You can't specify static members on interfaces, so the interface IAdd<T> defines a single method T Add(T b) where it assumes that you have an item of type T already and you want to add another of the same type to it. For instance if you have a struct xInstance of type X and you want to add a different X you would call xInstance.Add(anotherInstanceOfX);
Now that you have an interface defined you can make a generic AbstractVectorProcessor that has a generic method public static T Add<T>(T a, T b) where T : IAdd<T>
You can use type inference to specify the type, so rewriting the example from before it would be AbstractVectorProcessor.Add(xInstance, anotherInstanceOfX)
At this point, though, I'm not sure what value the AbstractVectorProcessor would be when you can just as easily call xInstance.Add(anotherInstanceOfX).
Edit:
I read the question again and realized you were looking for an abstract implementation of AddTwo, so I changed the AbstractVectorProcessor to implement an AddTwo where b is added twice.
using System;
public class Program
{
public static void Main()
{
var x = new X(10);
var tripleX= AbstractVectorProcessor.AddTwo(x, x);
Console.WriteLine(tripleX.Value);
}
public interface IAdd<T>
{
T Add(T b);
}
public struct X : IAdd<X>
{
public X(double val)
{
Value = val;
}
public double Value {get;}
public X Add(X b)
{
return new X(Value + b.Value);
}
}
public struct Y : IAdd<Y>
{
public Y(double val)
{
Value = val;
}
public double Value {get;}
public Y Add(Y b)
{
return new Y(Value + b.Value);
}
}
public static class AbstractVectorProcessor
{
public static T AddTwo<T>(T a, T b) where T : IAdd<T>
{
return a.Add(b).Add(b);
}
}
}

(C#)interface with virtual method

I need a interface objectIMyInterface obj;that can swallow all classes object that inherit from it, as my sample code that are working well but inside I need implement function I don't need because IMyInterface require it, I try these two ways but both failed:
create virtual class MethodThatNotBelongToUsAll{} and try class ClassA_wrap : ClassA, MethodThatNotBelongToUsAll, IMyInterface but receive error class 'ClassA_wrap' cannot have multiple base classes
change interface IMyInterface to virtual class IMyInterface{} but the line obj = new ClassA_wrap(); show error cannot implicitly convert type "ClassA_wrap" to "IMyInterface"
can anyone help me with this? thx!
interface IMyInterface
{
int Foo0 { get; } //ClassA,B,C method
int FooWrap(int F); //ClassA_wrap,B_wrap,C_wrap method
int FooA(int F); // ClassA method
int FooB(int F); // ClassB method
int FooC(int F); // ClassC method
}
class ClassA //Base Class, can't edit
{
public int Foo0{ get { return 1; } }
public int FooA(int F) { return F; }
}
class ClassB //Base Class, can't edit
{
public int Foo0 { get { return 2; } }
public int FooB(int F) { return F; }
}
class ClassC //Base Class, can't edit
{
public int Foo0 { get { return 3; } }
public int FooC(int F) { return F; }
}
class ClassA_wrap : ClassA, IMyInterface
{
public int FooB(int F) { return -1; } // I want to get rid of this line, but Interface require to imp this...
public int FooC(int F) { return -1; } // I want to get rid of this line, but Interface require to imp this...
public int FooWrap(int F)
{
return FooA(F)*10+1;
}
}
class ClassB_wrap : ClassB, IMyInterface
{
public int FooA(int F) { return -1; } // I want to get rid of this line, but Interface require to imp this...
public int FooC(int F) { return -1; } // I want to get rid of this line, but Interface require to imp this...
public int FooWrap(int F)
{
return FooB(F)*20+2;
}
}
class ClassC_wrap : ClassC, IMyInterface
{
public int FooA(int F) { return -1; } // I want to get rid of this line, but Interface require to imp this...
public int FooB(int F) { return -1; } // I want to get rid of this line, but Interface require to imp this...
public int FooWrap(int F)
{
return FooC(F)*30+3;
}
}
class MainClass
{
static void Main()
{
IMyInterface obj; //I need IMyInterface object that can swallow all three classes depend on flag
int flag = 2; // or 1 or 3
if(flag==1)
obj = new ClassA_wrap();
else if(flag==2)
obj = new ClassB_wrap();
else
obj = new ClassC_wrap();
//-----------------------------------------
Console.WriteLine( obj.Foo0);
//-----------------------------------------
if(obj is ClassA_wrap)
Console.WriteLine(obj.FooA(11));
if (obj is ClassB_wrap)
Console.WriteLine(obj.FooB(22));
if (obj is ClassC_wrap)
Console.WriteLine(obj.FooC(33));
//-----------------------------------------
Console.WriteLine(obj.FooWrap(1));
Console.Read();
}
}
Read it over here : Interface Segregation Principle
i think you need to look one of SOLID whichis I: interface segregation principle
this principle says that create seperate interce if you are having method in interface, which you calss is not going to implement.
i suggest design like this
public interface IMasterInterface
{
//contains all common method
int Foo0 { get; } //ClassA,B,C method
int FooWrap(int F); //ClassA_wrap,B_wrap,C_wrap method
}
public interface IFooA
{
//contians method related to A only
int FooA(int F); // ClassA method
}
public interface IFooB
{
//contians method related to B only
int FooB(int F); // ClassA method
}
public class A : IFooA,IMasterInterface
{
//common method
//now this will have method related to A only7
}
public class B: IFooB,IMasterInterface
{
//common method
//now this will have method related to B only
}

Inheritance - Invoke child methods instead of parent

It is going to be hard to explain why Im doing the things im about to show you, but they have a reason so stay with me here. (suggestions are welcome).
I have a Functor which invokes a method on its input.
!Please note! the functor is actually an extension method so there must be a typing inference.
Also, I have an abstract class with 2 childs and an interface which demands a method signature.
The example code looks like this:
public sealed class AbstractionTester
{
internal static void Run()
{
// The functor here accepts A type but in my original code its just a generic type.
// I wanted to keep it simple for this example only
Func<A, bool> func = a =>
{
a.CallMe(); //Displays "Error"
return true;
};
B obj = new B();
func(obj);
}
}
internal interface ICallMe<T>
where T : MyEntity
{
T CallMe();
}
//Just a class which holds data I would like to store about every object I have, for example: CreateDate
internal abstract class MyEntity
{ }
internal abstract class A : MyEntity, ICallMe<A>
{
//some other fields i would like to store..
// This method here must never be invoked
public A CallMe()
{
//throw new Exception();
Console.WriteLine("Error");
return this;
}
}
internal class B : A, ICallMe<B>
{
public new B CallMe()
{
Console.WriteLine("B");
return this;
}
}
internal class C : A, ICallMe<C>
{
public new C CallMe()
{
Console.WriteLine("C");
return this;
}
}
Everytime I call Run() the result is the Error is yeilded to the screen.
What can I do to enforce that this functor I have won't execute the method in the parent class.
Functor will never receive an instance of A anyway, because A is abstract (I mean pure A, not child of A)
Additional info:
I must explicity write the return types of CallMe in class B and C. I CANNOT change them to type A.
I need to keep the type of A (or something similar) in the functor because I need to infer the type for some code continuation.
It is really weird implementation. Why dont you use Visitor pattern?
Then you can do:
static void Main(string[] args)
{
Element a = new A();
Element b = new B();
Element c = new C();
ICallMe callMe = new CallMe();
a.accept(callMe);
b.accept(callMe);
c.accept(callMe);
}
Implementation below:
public interface ICallMe
{
void Visit(A a);
void Visit(B b);
void Visit(C c);
}
public class CallMe : ICallMe
{
public void Visit(A c)
{
Console.WriteLine("A");
}
public void Visit(B b)
{
Console.WriteLine("B");
}
public void Visit(C a)
{
Console.WriteLine("C");
}
}
interface Element
{
void accept(ICallMe visitor);
}
public class A : Element
{
public void accept(ICallMe visitor)
{
visitor.Visit(this);
}
}
public class B : Element
{
public void accept(ICallMe visitor)
{
visitor.Visit(this);
}
}
public class C : Element
{
public void accept(ICallMe visitor)
{
visitor.Visit(this);
}
}
Here is a solution that works without defining public A CallMe() as virtual. This has the benefit that child classes can define their CallMe() as new so they can return B or C. But it requires that you can make the classes public instead of internal (or you will get an error).
Use dynamic dispatch to call the actual runtime type instead of the type declared in the interface:
Func<A, bool> func = a => {
var runtimeType = (dynamic)a;
runtimeType.CallMe();
return true;
};
.net Fiddle
There is a specific language feature for this; interface reimplementation.
Reimplement explicitly the interface and make the generic functor take an ICallable<T>:
internal class B : A, ICallMe<B>
{
B ICallable<B>.CallMe()
{
Console.WriteLine("B");
return this;
}
}
internal class C : A, ICallMe<C>
{
B ICallable<C>.CallMe()
{
Console.WriteLine("B");
return this;
}
}
And your functor should be:
Func<T, bool> func = a => ...
And T should be constrained (at method or class level) to ICallable<T>.
UPDATE: If the functor is really an extension code, I'm not sure what the issue is:
public static bool MyEnxtensionMethod<T>(T argument)
where T: ICallable<T>
{
argument.CallMe();
return true;
}
Why do you need to keep A anywhere?
The best way to ensure that A's CallMe method is never invoked is for it to not exist.
internal abstract class MyEntity
{ }
internal abstract class A : MyEntity
{ }
Now it can never be invoked as you required.
Now make the interface covariant:
internal interface ICallMe<out T>
where T : MyEntity
{
T CallMe();
}
Then change Func<A, bool> to Func<ICallMe<A>, bool>
public sealed class AbstractionTester
{
internal static void Run()
{
// The functor here accepts A type but in my original code its just a generic type.
// I wanted to keep it simple for this example only
Func<ICallMe<A>, bool> func = a =>
{
a.CallMe(); //Displays "B"
return true;
};
B obj = new B();
func(obj);
}
}

Expose Methods in Properties as Single Class

I needed to break up a WCF service contract that had a massive interface and clientbase class into smaller classes. All of the smaller classes are similar but have different operation contracts. I want to be able to expose the operation contract methods in all the new sub-classes as a single class for backwards compatibility. Ideally it would look something like this:
public class MainClient {
public MainClient() {
Sub1 = new Sub1Client();
Sub2 = new Sub2Client();
}
public static Sub1Client Sub1;
public static Sub2Client Sub2;
}
I would then want to be able to call methods from Sub1 and Sub2 as if those methods were defined in MainClient. So instead of calling (new MainClient()).Sub1.Method1() I would call (new MainClient()).Method1() where Method1 still exists in the Sub1Client class.
Is this possible?
I not sure that clearly understand your question, but check this solution:
public interface IFirst
{
void Method1(string a);
}
public interface ISecond
{
double Method2(int b, bool a);
}
public interface IComplex : IFirst, ISecond
{
}
public class MyException : Exception
{
public MyException(string message) : base(message)
{
}
}
public class Sub1Client : IFirst
{
public void Method1(string a)
{
Console.WriteLine("IFirst.Method1");
Console.WriteLine(a);
}
}
public class Sub2Client : ISecond
{
public double Method2(int b, bool a)
{
Console.WriteLine("ISecond.Method2");
return a ? b : -b;
}
}
public class MainClient : IComplex
{
public MainClient()
{
Sub1 = new Sub1Client();
Sub2 = new Sub2Client();
}
public static Sub1Client Sub1;
public static Sub2Client Sub2;
private T FindAndInvoke<T>(string methodName, params object[] args)
{
foreach(var field in this.GetType().GetFields(BindingFlags.Public | BindingFlags.Static))
{
var method = field.FieldType.GetMethod(methodName);
if(method != null)
return (T)method.Invoke(field.GetValue(this), args);
}
throw new MyException("Method was not found!");
}
public void Method1(string a)
{
FindAndInvoke<object>(MethodBase.GetCurrentMethod().Name, a);
}
public double Method2(int b, bool a)
{
return FindAndInvoke<double>(MethodBase.GetCurrentMethod().Name, b, a);
}
}
public static void Main()
{
var test = new MainClient();
test.Method1("test");
Console.WriteLine(test.Method2(2, true));
}

Generic method declaration

I have hierarchy of classes:
class A{}
class B: A {}
class C:B {}
is it possible to implement method in class A and it would be inherited by derived classes B and C and so on and that method should return value of class type?
A val = A.method(); (val is A)
B val = B.method(); (val is B)
C val = C.method(); (val is C)
And I don't want use of generics in call of this method, ie:
C val = C.method<C>();
Guys, excuse me, one elaboration, this method should be static.
I don't want to use generic in method istelf, because it forces to point type that method should return, whereas method should return type of its class.
class A
{
Method<T>()
{
T result;
return result;
}
}
If I have such method I can change return type:
D result = A.Method<D>();
but I wanted it to return value of type A;
No, that is not possible.
To call the method like that it would have to be static, and static methods are not inherited.
Using B.method() to call a static method in A is the same as using A.method(). The compiler just uses the type to determine where the method is, but it's impossible for the method to know if it was called using the A or B type.
Use an extension method:
class Program
{
static void Main(string[] args)
{
B x = new B();
x.Method();
}
}
public static class Ext
{
public static T Method<T>(this T obj)
where T : A,new()
{
return new T();
}
}
public class A
{
}
public class B : A
{
}
Or a variation thereof. Note that you must have some public member capable of creating an instance of the specified type. To expound, the compiler 'guesses' the value of the type parameter. The method is still generic, but generic syntax is nowhere to be seen when the method is called (usually).
Using some design patterns from C++ makes this easier:
class A
{
protected virtual A method_impl() { return new A(); }
public A method() { return method_impl(); }
}
class B : A
{
protected override A method_impl() { return new B(); }
public new B method() { return (B)method_impl(); }
}
class C : B
{
protected override A method_impl() { return new C(); }
public new C method() { return (C)method_impl(); }
}
Of course, this exact problem never arises in C++, which allows covariant return types for overrides.
Another way, using IoC pattern:
class A
{
protected virtual void method_impl(A a) { a.initialize(); }
public A method() { A result = new A(); method_impl(result); return result; }
}
class B : A
{
public new B method() { B result = new B(); method_impl(result); return result; }
}
class C : B
{
public new C method() { C result = new C(); method_impl(result); return result; }
}

Categories

Resources