Interface property refering to Base class - c#

Run it here: http://rextester.com/ZMLMB2576
public interface IClass {
int number {get;}
}
public abstract class BaseClass : IClass {
public BaseClass(int n){
number = n+100;
}
public int number { get;set;}
}
public class DerivedClass : BaseClass {
public DerivedClass(int n) : base(n) {
number = n;
}
public int number { get;set;}
}
public class Program
{
public static void Main(string[] args)
{
var foobar = new DerivedClass(1);
Console.WriteLine(GetNumber(foobar)); // 101
}
public static int GetNumber(IClass foo){
return foo.number;
}
}
Why does the function GetNumber not use the most derived class and instead only treats the passed object as BaseClass ?
If it was treating the passed object (foo) as DerivedClass then I suspect the base constructor to run first and then DerivedClass constructor, overriding 101 with 1

Shadowing (number in derived class hides one from base) and the fact that interface is implemented by base class leads to this behavior. Mapping interface methods defined by base class and IClass.number is mapped to BaseClass.number which is completely different from DerivedClass.number.
Fixes:
make property number to be virtual in base class (more standard approach)
derive both classes from the interface so interface actually picks up implementation from derived class (will confuse readers and everyone will try to remove interface from derived thus breaking it again)
class Derived : BaseClass, IClass { ...
Notes:
it is better to explicitly specify new public int number {get;set;} when you shadow members of base class.
C# is not Java and methods/fields are not virtual by default.
Difference between shadowing and overriding in C#?

Related

C# abstract class desgin, is that possible put a constuctor in abstract class and call base to access them

I was practicing c# abstract class and inheritance, but I was wondering if derived classes could access the constructor by calling the base
public abstract class A
{
protected bool value_A;
protected int value_B;
public A(int input)
{
A = true;
B = false;
}
public abstract int function_B();
}
}
public class childA : A
{
public childA (int input):base(input)
{
}
public override int function_B()
{
//do smth
}
}
public class childB : A
{
public childB(int input):base(input)
{
}
public override int function_B()
{
//do something different
}
public void functionC(int input)
{
}
}
I was confused if I should use this abstract class design or just go ez by using inheritance -> declare a virtual function in class A.
Yes, you can. Derived class c'tor can call base class one, even if the base class is abstract.
Generally, using abstract base class makes sense if there is a common functionality (or traits) that you want to reuse, and instantiating the base class does not make sense (and therefore you make it an abstract class).
A basic example is "Shapes" hierarchy, with abstract base class Shape that has color and center (for instance) and virtual method Draw, and all specific shapes inheriting from Shape and implementing the actual Draw functionality for each specific shape.

How to require an implementation of an abstract class in C#?

I want to build a class that would have a property, in which there is an instance of a class, which implements an abstract class. Here's and example.
public class MyClass {
public MyDerivedClassA derived;
public void mainClassUtility () {
derived.foo();
}
}
public abstract class MyAbstractBaseClass {
public abstract void foo();
}
public class MyDerivedClassA : MyAbstractBaseClass {
public override void foo(){
return;
}
}
public class MyDerivedClassB : MyAbstractBaseClass
{
public override void foo()
{
return;
}
}
Basically, I want to make sure the object I'm using is derived from an abstract class and implements all the methods I will need to use. There will be many implementations of the abstract class and depending on the current state of the program, MyClass might be using different implementations of the ABC. I want to write the program in a way, that no matter what implementation of the ABC is currently being used, there is a way to call it's methods by MyClass. What would be the best solution to this problem?
Unless I'm misunderstanding the question, you're pretty much there. Have MyClass expect a property of the abstract base class and you should be all set.
using System;
public class Program
{
public static void Main()
{
var myClassOne = new MyClass(new MyDerivedClassA());
var myClassTwo = new MyClass(new MyDerivedClassB());
myClassOne.mainClassUtility();
myClassTwo.mainClassUtility();
}
public class MyClass
{
public MyAbstractBaseClass Derived;
public MyClass(MyAbstractBaseClass derived)
{
Derived = derived;
}
public void mainClassUtility ()
{
Derived.foo();
}
}
public abstract class MyAbstractBaseClass
{
public abstract void foo();
}
public class MyDerivedClassA : MyAbstractBaseClass
{
public override void foo()
{
Console.WriteLine("I am MyDerivedClassA");
return;
}
}
public class MyDerivedClassB : MyAbstractBaseClass
{
public override void foo()
{
Console.WriteLine("I am MyDerivedClassB");
return;
}
}
}
How to require an implementation of an abstract class in C#?
You can not instantiate a abstract class - and thus can not use it for most cases. Except as variable/argument/generic type argument. You need to make a concrete (non-abstract) class that inherits from it. You can only use the abstract class as a variable/argument type. To guarantee that only stuff that inherits from it can be used there.
Basically, I want to make sure the object I'm using is derived from an abstract class and implements all the methods I will need to use.
Then use the abstract class as type argument. It means only instaces of the abstract class (of wich there can be no instance) or instances of classes that inherit from it (that somebody else writes) can be used at that place.
Note that Abstract classes and Interfaces overlap in nearly all uses. There is a miriad small differences, but I do not think they mater. The only big difference I can see, is one of exclusivity:
a class can implement as many Interfaces as it wants.
You can only inherit from one abstract class. that means it is for a primary, exclusive purpose. That way you prevent some dumb ideas, like someone trying to make a Windows Form that is also a DBConnection.

When defining an abstract class, can you force a child to define a property/method defined in a parent interface?

Consider the following class definition.
public abstract class FooBase : IBar
{
public int Value {get; set;}
public string ToString()
{
//Return a string.
}
}
public interface IBar
{
int Value;
string ToString();
}
FooBase is a base class that provides implementation of the IBar interface.
As an abstract class, FooBase cannot be directly instantiated. Therfore, another class must derive from this class for it to be useful.
Now, consider the scenario where you need an object like FooBase that implements the the IBar interface, however, for once specific member IBar you need the children of FooBase to implement it, not FooBase itself.
Is there a way to implement/address a member in an abstract class like FooBase, derived from IBar, in such a way that any child of FooBase must implement a single member from IBar, rather than relying on the base implementations of FooBase?
I assume there isn't because the compiler is telling that declaring a value like public abstract int Value is not allowed but I figured it was worth asking and verifying. But, maybe I'm wrong and if so, is there a proper way to force the child implementation of my base class to implement a member from a parent interface on my base?
assume there isn't because the compiler is telling that declaring a value like public abstract int Value is not allowed
Of course it is allowed, this compiles perfectly fine:
interface IBar
{
int Foo { get; set; }
string Blah();
}
abstract class Base: IBar
{
public abstract int Foo { get; set;}
public string Blah() => null;
}
And now:
class Derived: Base
{
//must implement Foo
}
Your code by the way doesn't compile, you can't define fields in an interface.
This compiles just fine:
public abstract class FooBase : IBar
{
public abstract int Value { get; set; }
}
public interface IBar
{
int Value { get; }
}
Any class that derives from FooBase must override Value:
public class Concrete : FooBase
{
public override int Value { get; set; }
}

Need to add same properties in two different classes

I have two classes like Class A and Class B. Class A have some properties, methods and Class B have only the properties. But both Classes have the same set of properties.
My Question is, If I add any new property in Class A, I need to add that in Class B also. If I did not add means, need to show error. How can I achieve this through C#?
You may achieve this by using an Interface and implementing it both in class A and class B. In the interface, define the property that is required in class A and B:
public interface ICommonProperty
{
string MyProperty{ get; set; }
}
Or you can use keyword abstract to create a class in common for A and B.
abstract class BaseClass // Abstract class
{
public int X {get;set;} // property in common for 2 class
}
class A : BaseClass
{
}
class B : BaseClass
{
public int Y {get;set;} // other property of B
}
You can go with the abstract class. The abstract keyword enables you to create classes and class members that are incomplete and must be implemented in a derived class.
Here is a simple example related to your question However you can understand and learn about Abstract classes here : Abstract Class
using System;
public class Program
{
public static void Main()
{
A objA = new A();
objA.printA();
B objB = new B();
objB.printB();
}
}
abstract class Parent{
public int a = 5;
}
class A : Parent
{
public void printA()
{
Console.WriteLine("In class A, value is "+a);
}
}
class B : Parent
{
public void printB()
{
Console.WriteLine("In class B, value is "+a);
}
}
Output of the above program is:
In class A, vlaue is 5
In class B, vlaue is 5
Hope this helps you.

What would be the right modifier?

I have the following class with some methods and I would like to use this as a base class of another class.
public class BaseClass
{
public string DoWork(string str)
{
// some codes...
}
// other methods...
}
I don't want this class to be instantiated, but the derived class should still use the original implementation of the methods of its base class.
Is it possible? What should be my modifier?
Since you don't want this class to be instantiated, make it an abstract class. You can still have implementation on the class.
abstract
snippet,
public abstract class BaseClass
{
public virtual string DoWork(string str)
{
// can have implementation here
// and classes that inherits can overide this method because of virtual.
}
// other methods...
}
Make BaseClass abstract:
public abstract class BaseClass
{
// Only available to BaseClass
private string _myString;
public string DoWork(string str)
{
// Available to everyone
return _myString;
}
protected void DoWorkInternal() {
// Only available to classes who inherit base class
}
}
This way, you can define your own code within BaseClass - but it cannot be initialized directly, it must be inherited from.

Categories

Resources